Twin Prime Conjecture-孪生素数

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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值