【Codeforces 947A】 Primal Sport
【题目链接】
【算法】
不难看出,x1的范围是[x2-P(x2)+1,x2],x0的范围是[x1-P(x1)+1,x1]
我们可以先做一遍线性筛,然后暴力就可以了
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 1e6; int i,j,k,tmp,x,l,ans; bool mark[MAXN+10]; vector<int> Prime; template <typename T> inline void read(T &x) { int f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } int main() { read(x); for (i = 2; i <= MAXN; i++) { if (!mark[i]) Prime.push_back(i); for (k = 0; k < Prime.size(); k++) { tmp = i * Prime[k]; if (tmp > MAXN) break; mark[tmp] = 1; if (i % Prime[k] == 0) break; } } for (i = 0; i < Prime.size(); i++) if (x % Prime[i] == 0) l = x - Prime[i] + 1; ans = x; for (i = 0; i < Prime.size(); i++) { for (j = 2 * Prime[i]; j <= x; j += Prime[i]) { if (j < l) continue; ans = min(ans,j-Prime[i]+1); } } writeln(ans); return 0; }