VK Cup 2018 - Round 1 A. Primal Sport

A. 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.


可能英语不行啊,“announces the smallest multiple of this prime number that is not smaller than the current number.”这句话看成素数的最小倍数不小于该数。

但经过大佬的提点=》tzuhsiao


题意:我们只看x0,x1,x2这三个变量,题目给你x2的值,然后你找一个素数p1,要求p1<x1,而且x2是p1的倍数,这个x2是接近x1但大于x1的最小数(上面的英文也是这个意思)

简单来讲就是,对于当前的x,选取一个质数p,p<当前值,然后让这个质数的最小倍数大于等于当前值。(等于的时候说明是这个质数本身是当前数的质因数的情况)



思路:

对于每个合数而言,都可表示成若干个质数的乘积。所以当知道了x2的值以后,x1的取值范围为[x2-P(x2)=1,x2],(其中P(x2)表示x2的最大质因数)。

同理,x0的取值范围是[x1-P(x1)+1,x1]。从这个取值范围的表达式可以看出,取得素数的值越大,上一个数字的最小值就会越小。所以这里取得是最大质因数。

这样的话就可以先使用质数筛预处理,然后按这个思路找最小值。



#include <iostream>

using namespace std;


const int maxn=1000006;
int prime[maxn];


void getprime()
{
    int n=2;
    while(n<maxn)
    {
        int num=2*n;
        while(num<maxn)
        {
            prime[num]=n;
            num+=n;//该数的倍数也更新一次
        }
        num=n+1;
        while(prime[num]!=0&&num<maxn)
        {
            num++;//略过那些没有质因数的情况
        }
        n=num;
    }


}


int main()
{
    getprime();
    //int n;
    //cin>>n;
    int x0,x1,x2;
    int a,b;
    cin>>x2;//因为取得质因数越大,则他的下一个数的最小值越小
    b=prime[x2];
    x0=999999;
    int i;
    for(i=x2-b+1;i<=x2;i++)
    {
        a=prime[i];
        x0=min(x0,i-a+1);
    }
    cout<<x0<<endl;
    return 0;
}















posted @ 2018-03-17 14:24  Bryce1010  阅读(87)  评论(0编辑  收藏  举报