B - Twin Prime Conjecture

          B - Twin Prime Conjecture

If we define dn as: dn = pn+1-pn, where pi is the i-th prime. It is easy to see that d1 = 1 and dn=even for n>1. Twin Prime Conjecture states that "There are infinite consecutive primes differing by 2". 
Now given any positive integer N (< 10^5), you are supposed to count the number of twin primes which are no greater than N.
InputYour program must read test cases from standard input. 
The input file consists of several test cases. Each case occupies a line which contains one integer N. The input is finished by a negative N.OutputFor each test case, your program must output to standard output. Print in one line the number of twin primes which are no greater than N.Sample Input
1
5
20
-2
Sample Output
0
1
4

题意:统计 0到n 之间,素数a-素数b==2,  这样的Twin Prime一共有多少!

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 100000
int vis[N+1]={1,1};
int prime[N+1];
void fun()
{
     int n=2,sum=0;
     for(long long i=2;i<=N;i++)//一定要是 <=N ,而不是 m=sqrt(N+0.5),因为是统计从1到n的数;
     {
         if(!vis[i])
         {
            if(i-n==2)
                sum++;
            n=i;
            for(long long j=i*i;j<=N;j+=i)//用长整型,否则会溢出的。
                 vis[j]=1;
         }
         prime[i]=sum;
     }
}
int main()
{
    fun();
    int n;
    while(scanf("%d",&n)==1)
    {
        if(n<0)
            break;
        printf("%d\n",prime[n]);
    }
    return 0;
}


 

猜你喜欢

转载自blog.csdn.net/hnust_lec/article/details/79638548