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

来源:互联网 发布:java调用python程序 编辑:程序博客网 时间:2024/05/21 09:37

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
610120
 

Sample Output
121



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

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

对于这个问题,我参照了一下两个博客
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;}}




0 0
原创粉丝点击