Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output a single integer — the minimum possible X0.
14
6
20
15
8192
8191
这个题题意就是给你一个x2,输出x0,首先得找到x1,x1=[x2-(x2的最大素数因子)+1,x2],x0=[x1-(x1的最大素数因子)+1,x1]。
求解x的最大素数因子是关键。所以我们选择求出从2到x2的最大素数因子,这样就能求出一次后不用再求x1的最大素数因子。对于求最大素数因子,从2开始。如果本身是一个素数,就将最大素数因子变为0.所以我们找素数的倍数,即2的倍数是4,6,8,10等等。但是6的最大素数因子是3,所以等到3的时候再循环一次就是6的最大素数因子为3.
#include <cstdio>
#include<stdio.h>
using namespace std;
const int maxn = 1e6 + 10;
int n, ans;
int f[maxn];
inline int Min(int x, int y) { return x<y ? x : y; }
int main() {
scanf_s("%d", &n);
ans = n;
for (int i = 2; i <= n; i++) {
if (!f[i]) {
for (int j = 2 * i; j <= n; j += i) f[j] = i;
}
f[i] = i - f[i] + 1;
}
for (int i = f[n]; i <= n; i++) ans = Min(ans, f[i]);
printf("%d\n", ans);
return 0;
}