Gym - 100085G - GCD Guessing Game
题意
一个数字x在1-n之间,现在猜数字,每次猜一个数字a,告知gcd(x, a)的答案,问最坏情况下需要猜几次
分析
考虑素数。当猜的数为一组素数的乘积时,就可以把这些素数都猜出来。那么答案就是总共的组数。接下来就贪心构造每一组,每次取最后一个,尽量和小的合并。
代码
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 10005; int vis[N], prime[N], pn = 0; void getprime() { for (int i = 2; i < N; i++) { if (vis[i]) continue; prime[pn++] = i; for (int j = i * i; j < N; j += i) vis[j] = 1; } } int n; int main() { freopen("gcd.in","r",stdin); freopen("gcd.out","w",stdout); getprime(); while (~scanf("%d", &n)) { int ans = 0, head = 0, rear = pn - 1; while (prime[rear] > n) rear--; while (head <= rear) { int p = prime[rear]; while (p * prime[head] <= n) p *= prime[head++]; ans++; rear--; } printf("%d\n", ans); } return 0; }