题目:
Mr. F has nn positive integers, a1,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.
The first line contains an integer nn (2≤n≤3⋅10^5) — the number of integers Mr. F has.
The second line contains nn integers, a1,a2,…,an (1≤ai≤1.5⋅10^7).
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).
3
1 2 4
1
4
6 9 15 30
2
3
1 1 1
-1
In the first example, the greatest common divisor is 1 in the beginning. You can remove 1 so that the greatest common divisor is enlarged to 2. The answer is 1.
In the second example, the greatest common divisor is 3 in the beginning. You can remove 6 and 9 so that the greatest common divisor is enlarged to 15. There is no solution which removes only one integer. So the answer is 2.
In the third example, there is no solution to enlarge the greatest common divisor. So the answer is −1.
题意分析:
这题意思就是给你N个数,这N个数会有一个最大公约数G,那么需要去掉K个数,使余下的N-K个数的最大公约数变大。求最小K。
我们从gcd的原理分析,这N个数都除以gcd后,余下的数的最大公约数无法变大时因为不存在公因子,所以我们需要对这N个数进行分类,分类的标准就是是否还有共同的公因子,然后找出包含的数目最多的类别,假设这个类别有M个数。
那么N-M就是我们最终的结果。
这里需要注意的技巧是,在进行类别划分的时候,我们用的素数打表的原理。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 3e5+5;
const int MAX = 1.5e7+5;
int A[MAXN], cnt[MAX];
bool visit[MAX];
int gcd(int a, int b)
{
return b==0?a:gcd(b, a%b);
}
int Max(const int a, const int b)
{
return a>b?a:b;
}
int main()
{
int N;
while(~scanf("%d", &N))
{
int G, ans;
scanf("%d", &A[0]);
G = A[0];
for(int i = 1; i < N; i++)
{
scanf("%d", &A[i]);
G = gcd(G, A[i]);
}
memset(cnt, 0, sizeof(cnt));
memset(visit, true, sizeof(visit));
for(int i = 0; i < N; i++)
cnt[A[i]/G]++;
visit[0] = visit[1] = false;
ans = 0;
for(int i = 2; i < MAX; i++)
{
int res = cnt[i];
if(visit[i])
{
for(int j = 2*i; j < MAX; j+=i)
{
visit[j] = false;
res += cnt[j];
}
}
ans = Max(ans, res);
}
printf("%d
", ans==0?-1:N-ans);
}
return 0;
}