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.
题意:当时做的时候不知道用什么方法做,看了人家的博客,才知道用 类似于素数筛的做法, 1.5e7 的素筛,也能过,我不会计算复杂度了,哪位看博客的朋友,给讲解一下,在这(❁´ω`❁)谢过了;
先求出 所有数的最大公约数 g,再 g+1 开始筛,请看代码:
#include<bits/stdc++.h>
using namespace std;
#define Max (int)(1.5e7+10)
#define ll long long
int book[Max],num[Max];
int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
int main()
{
int n;
scanf("%d",&n);
int g = 0,tt;
for(int i = 0;i<n; i ++ )
{
scanf("%d",&tt);
num[tt] ++;
if(!i) g = tt;
else g = gcd(g,tt);
}
int ans = n;
for(int i = g + 1; i<Max;i++)
{
if(book[i]) continue;
int cnt = 0;
for(int j = i;j < Max; j += i)
{
book[j] = 1;
cnt += num[j];
}
ans = min(ans, n - cnt);
}
if(ans == n)
printf("-1\n");
else printf("%d\n",ans);
return 0;
}