Prime pair conjecture

Time:2021-5-13

1、 Title:

Topic link

  Let’s define DnIt is: Dn​​=p​n+1​​−p​nWhere piIs the i-th prime. Obviously there is diFor n > 1, D ﹣ n ﹣ is even“ The prime pair conjecture holds that there are infinite pairs of adjacent prime numbers with difference of 2.

Now any positive integer n (< 10) is given5), please calculate no more thanNThe number of prime pairs satisfying the conjecture.

2、 Input format:

Enter a positive integer on one lineN

Output format:

Output no more thanNThe number of prime pairs satisfying the conjecture.

3、 Input example:

   20

Output example:

  4

4Design idea:

Because the problem requires a prime number which is adjacent and the difference is two, we can directly make the first number I and the last number I + 2,

Then judge whether these two numbers are prime numbers, if so, then add 1 to the variables of the statistical prime number pair; A do while is nested outside

The loop is OK. Note that the termination condition of the loop is I + 2 < = num, not I < = num. if I < = num, it may be out of bounds,

It does not meet the requirements of the topic. Another point is that in the function for judging prime numbers, if the loop condition for judging prime numbers is changed to the following code:

  for(i=2;i

            if(num%i==0){
                flag=0;
                break;
            }

Although the final result will not be a problem, it will have a great impact on the time complexity of the program. This is what I wrote at the beginning when I did this problem online,

Because that website has a limitation on the running time of the program, so it can’t pass. You need to improve the code to reduce the time complexity

I just want to improve the loop of prime judgment function, which essentially reduces the number of loops. The improved code is as follows:

  for(i=2;i<=sqrt(num);i++)
            if(num%i==0){
                flag=0;
                break;
            }

   

5、 Full code:

 

#include
#include
int JudgePrimeNum(int num);
int main()
{

    int num;
    int i=1;
    int flag=0;
    scanf("%d",&num);
    do
    {
        if(JudgePrimeNum(i)==1&&JudgePrimeNum(i+2)==1)
            flag=flag+1;
        i++;     
    } while (i+2<=num);
    printf("%d",flag);
    return 0;
}
//Judge whether the number is prime or not
int JudgePrimeNum(int num)
{
    int flag=1;
    if(num==1){
        flag=0;
    }
    else if(num==2||num==3){
        flag=1;
    }
    else{
        int i;
        for(i=2;i<=sqrt(num);i++)
            if(num%i==0){
                flag=0;
                break;
            }
    }
    return flag;
}

 

6、 Output effect: