判断素数的几种方法 杭电OJ 1397


Problem Description
Goldbach's Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2.
This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if any, for a given even number. The problem here is to write a program that reports the number of all the pairs of prime numbers satisfying the condition in the conjecture for a given even number.

A sequence of even numbers is given as input. Corresponding to each number, the program should output the number of pairs mentioned above. Notice that we are interested in the number of essentially different pairs and therefore you should not count (p1, p2) and (p2, p1) separately as two different pairs.
 

Input
An integer is given in each input line. You may assume that each integer is even, and is greater than or equal to 4 and less than 2^15. The end of the input is indicated by a number 0.
 

Output
Each output line should contain an integer number. No other characters should appear in the output.
 

Sample Input
   
   
6 10 12 0
 

Sample Output
   
   
1 2 1



问题并不难,就是判断给定数的两个加数是不是素数,如果是,的话统计出这样的数据有多少。

问题出在如何快速判断素数。

对于这个问题,我参照了一下两个博客
http://wenku.baidu.com/link?url=eQXFvY_Ac5eNsaOMcqphCsk_2Hu3f0W-ZZ3BDbI2XrsjxlsJmNnpSbgF4bg8bginSa2sueYiZWsytEmzMVbYt3OmOd09hOsqfLoJjF_rQpO

http://blog.csdn.net/l04205613/article/details/6025118

起初我是用的是遍历并逐个判断两个加数是不是素数,超时了。

最后我用的是筛法列出素数表,才解决了这个问题。

贴出AC代码

#include <iostream>
#include <math.h>
using namespace std;
/*
//普通的单个判断方法(一般情况挺好用的)(比2到根号X的方法要快)
bool Prime(int n)
{
	int p[8]={4,2,4,2,4,6,2,6};
	if(n==0||n==1)
		return false;
	if(n==2||n==3||n==5)
		return true;
	if(n%2==0||n%3==0||n%5==0)
		return false;
	for(int i=7;i<=(int)sqrt(n);)
	{
		for(int j=0;j<8;j++)
		{
			i+=p[j];
			if(n%i==0)
				return false;
		}
	}
	return true;
}


*/


int A[1000001];
long SIZE = 1000000;

//列出素数表
void Prime()
{
	A[1]=false;<span style="white-space:pre">			</span>//1既不是素数也不是合数
	for(int i=2;i<=SIZE;i++)<span style="white-space:pre">	</span>//初始化成都是素数
		A[i]=true;
	for(int i=2;i<=SIZE;i++)<span style="white-space:pre">	</span>//从2开始逐个抠除非素数的数
	{
		if(A[i])<span style="white-space:pre">		</span>//如果是素数
		{
			for(int h = i+i;h<=SIZE;h+=i)<span style="white-space:pre">		</span>//将它的倍数全部抠除
			{
				A[h]=false;
			}
		}
	}
}



int main()
{
	//freopen("D:\\output.txt","w",stdout);
	Prime();

	int n;
	cin>>n;
	while(n!=0)
	{
		int count =0;
		for(int i=2;i<=(int)(n/2);i++)
		{
			if(A[i]&&A[n-i])
				count++;
		}
		cout<<count<<endl;
		cin>>n;

	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值