B. Primal Sport
time limit per test
1.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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 - 1 such 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.
Input
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
Output a single integer — the minimum possible X0.
Examples
Input
Copy
14
Output
6
Input
Copy
20
Output
15
Input
Copy
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
Alice picks prime 5 and announces X1 = 10
Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
Alice picks prime 2 and announces X1 = 16
Bob picks prime 5 and announces X2 = 20.
题解:找到每个数x的最大质因子f,那么上一个数的取值范围就是(x-f+1,x),同上再找一层就好了,最大质因子的寻找可以用如下方法(注意,最大质因子的寻找和判断是否为素数是不一样的)
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i>=b;i--)
#define rson rt<<1|1,m+1,r
#define lson rt<<1,l,m
using namespace std;
const int N=1e6+100;
int arr[N];
int main()
{
int n;
cin>>n;
int ans=n;
for(int i=2;i<=n;i++)
{
if(!arr[i])//如果这个数没有出现过,即这个数是质数
{
for(int j=2*i;j<=n;j+=i)
arr[j]=i;//存的是这个数最大的质因子
}
arr[i]=i-arr[i]+1;//存的是上一个数的最小值
}
for(int i=arr[n];i<=n;i++)//找x1
ans=min(ans,arr[i]);//根据x1找x0
cout<<ans<<endl;
return 0;
}