Codeforce #511(Div 2) C. Enlarge GCD(GCD+思維)
C. Enlarge GCD
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Mr. F has nn positive integers, a1,a2,…,ana1,a2,…,an.
He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.
But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.
Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.
Input
The first line contains an integer nn (2≤n≤3⋅1052≤n≤3⋅105) — the number of integers Mr. F has.
The second line contains nn integers, a1,a2,…,ana1,a2,…,an (1≤ai≤1.5⋅1071≤ai≤1.5⋅107).
Output
Print an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.
You should not remove all of the integers.
If there is no solution, print «-1» (without quotes).
Examples
input
Copy
3 1 2 4
output
Copy
1
input
Copy
4 6 9 15 30
output
Copy
2
input
Copy
3 1 1 1
output
Copy
-1
Note
In the first example, the greatest common divisor is 11 in the beginning. You can remove 11 so that the greatest common divisor is enlarged to 22. The answer is 11.
In the second example, the greatest common divisor is 33 in the beginning. You can remove 66 and 99 so that the greatest common divisor is enlarged to 1515. There is no solution which removes only one integer. So the answer is 22.
In the third example, there is no solution to enlarge the greatest common divisor. So the answer is −1−1.
題意:給出一個長度為n的序列,在保證GCD比原來大的情況下,最少刪除幾個元素?若不能大則輸出-1.
題解:對每個數分解質因子,則將不包含數量最多的質因子的數都刪掉,剩下的數的GCD一定大於等於原先的GCD,同時又滿足刪除最少的元素。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1.5e7+7;
int a[maxn],prime[maxn],cot,cnt[maxn];
bool vis[maxn];
void primeall()
{
memset(vis,true,sizeof(vis));
for(int i=2;i<maxn-7;i++)
{
if(vis[i])
prime[++cot]=i;
for(int j=1;j<=cot;j++)
{
if(i*prime[j]>maxn-7) break;
vis[i*prime[j]]=false;
if(i%prime[j]==0) break;
}
}
}
int main()
{
primeall();
int n;
scanf("%d",&n);
int gcd=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
gcd=__gcd(gcd,a[i]);
}
for(int i=1;i<=n;i++)
{
a[i]/=gcd;
for(int j=1;prime[j]*prime[j]<=a[i];j++)
{
int p=prime[j];
if(a[i]%p==0) cnt[p]++;
while(a[i]%p==0) a[i]/=p;
}
if(a[i]>1) cnt[a[i]]++;
}
int ans=n;
for(int i=2;i<maxn;i++)
ans=min(ans,n-cnt[i]);
printf("%d\n",ans==n?-1:ans);
return 0;
}