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 palready 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[i],那么x[i+1]由质数p(p<x[i]) * k>=x[i] 其中取最小的  . 已知x2,求最小的x0

思路:对于质数,只能由质数本身转移过来;  否则可以由 [x-p[x]+1 , x]转移过来,

复杂度O(n*sqrt(n))

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int MAX_N=1e6+6;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f;

bool prime[MAX_N];

inline void init(){
    for(int i=2;i<=1e6;i++) prime[i]=true;
    for(int i=2;i<=1e6;i++){
        if(prime[i]){
            for(int j=i+i;j<=1e6;j+=i)  prime[j]=false;
        }
    }
}

inline int cul(int x){
    int ans=-1;
    for(int i=2;i*i<=x;i++){
        if(x%i==0){
            if(prime[i])    ans=max(ans,i);
            if(prime[x/i])  ans=max(ans,x/i);
        }
    }
    return ans;
}

int main(void){
    init();
    int n;
    cin >> n;
    int l=n-cul(n)+1;
    int ans=INF;
    for(int x1=l;x1<=n;x1++){
        if(!prime[x1])
            ans=min(ans,x1-cul(x1)+1);
        else    ans=min(ans,x1);
    }
    cout << ans << endl;
    return 0;
}