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.
孪生素数就是指相差2的素数对,例如3和5,5和7,11和13…。给定整数N,输出小于N的素数对的数量。
Input
Your 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.
Output
For 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.
样例输入
1
5
20
-2
样例输出
0
1
4
以下代码可得到正确结果但超时了,对素数的判断和素数对的个数计算有重复。
#include<iostream>
#include<math.h>
using namespace std;
bool isprim(int n){
int s=sqrt(n);
for(int i=2;i<=s;i++){
if(n%i==0)
return false;
}
return true;
}
int main(){
int n,count;
while(scanf("%d",&n)!=EOF&&n>=0){
int m=3;
count=0;
if(n<5)
printf("0\n");
else{
for(int i=3;i<=n;){
if(isprim(i)){
if((i-m)==2)
count++;
m=i;
}
i=i+2;
}
printf("%d\n",count);
}
}
return 0;
}
用空间换时间得到AC的程序
#include<iostream>
#include<math.h>
#include<memory.h>
using namespace std;
const int N=1e5;
const int sqr=sqrt(N);
bool judge[N+1];
int num[N+1];
void isprim(void){
memset(judge,true,sizeof(judge));
judge[0]=judge[1]=false;
//一次性记录是否是素数
for(int i=2;i<=sqr;i++){
if(judge[i]){
for(int j=i*i;j<=N;j+=i){
judge[j]=false;
}
}
}
//一次记录素数对个数
num[0]=num[1]=num[2]=num[3]=num[4]=0;
for(int i=5;i<=N;i++){
if(judge[i-2]&&judge[i]){
num[i]=num[i-1]+1;
}
else{
num[i]=num[i-1];
}
}
}
int main(){
isprim();
int n;
while(scanf("%d",&n)!=EOF&&n>=0){
printf("%d\n",num[n]);
}
return 0;
}