PAT B of the 1007 prime conjecture (C language), fifth test point overtime to solve

1007 prime to conjecture (20 minutes)

Let d n is defined as: dn = p n + 1- p n, where p i is the i-th prime number. Clearly there is d 1 = 1, and for n> 1 there is an even number dn. "Primes to guess" that "there is an infinite number of adjacent and poor is a prime number 2."
Now given an arbitrary positive integer N (<105), does not exceed Calculate number N satisfies the conjecture of primes.

Input formats:

It gives a positive integer in the input line N.

Output formats:

In the output line does not exceed the number N satisfy the conjecture of the primes.

Sample input:

20

Sample output:

4

/ This question many ways, it is very simple, you can first save all primes less than N up to judge, side judge can traverse side (and I'm this way, to get three if the code is simple, take up less memory, this recommendation method) /
/ after writing the fifth point there was a timeout, internet search, the problem is when I judge a prime number, the cycle is from 2 to x / 2 (in fact, with 2 to sqrt (x) on They, sqrt (x) are repeated later) results in the timeout. /
/ Solution: When seeking prime, do not have from 2 to x-1 (x / 2 will timeout) to go cycling, only 2 to sqrt (x), otherwise for the last time out test points /

#include <stdio.h>

int ss(int x)
{
    if(x==1 || x==2 || x==3 )
        return 1;
    for(int j=2;j<=sqrt(x);j++)
    {
        if(x%j==0)
            return 0;
    }
    return 1;
}

int main()
{
    int N,count=0;
    scanf("%d",&N);
    for(int i=1;i<=N-2;i++)
    {    
        if(ss(i))
            if(!ss(i+1))
                if(ss(i+2))
                    count++;
    }
    printf("%d\n",count);
    return 0;
}

/*这道题方法很多,也很简单,可以先把所有N以内的素数存起来判断,也可以边遍历边判断(我就是这种方法,三个if搞定代码简单,占用内存也少,推荐这个方法)*/
/*写完以后第五个点出现了超时的情况,网上搜了下,问题出在我判断素数的时候,循环过程是从2到x/2(其实用2-sqrt(x)就可以了,sqrt(x)后面的都是重复的)导致超时了。*/
/*解决方法:求素数时,不必从2到x-1(x/2也会超时)去循环,只需2到sqrt(x)即可,否则最后一测试点会超时*/
Released six original articles · won praise 0 · Views 75

Guess you like

Origin blog.csdn.net/weixin_44562957/article/details/104041588