poj2262 Goldbach's Conjecture 素数的欧拉筛法
2014-07-16 21:32
411 查看
题目链接:http://poj.org/problem?id=2262
思路:题意很简单。主要是用一般的素数判定方法速度很慢,据说会有TLE的风险。所以我先用欧拉筛法对 [ 2 , 1000000 ] 以内的素数进行打表。然后从2开始枚举每个素数a,直接通过打表得到的isPrime[ ]数组判断 n - a 是不是素数。
前几次用G++提交都是313MS,用C++提交了一次果断就141MS了 ^o^
思路:题意很简单。主要是用一般的素数判定方法速度很慢,据说会有TLE的风险。所以我先用欧拉筛法对 [ 2 , 1000000 ] 以内的素数进行打表。然后从2开始枚举每个素数a,直接通过打表得到的isPrime[ ]数组判断 n - a 是不是素数。
前几次用G++提交都是313MS,用C++提交了一次果断就141MS了 ^o^
///2014.7.16 ///poj2262 //Accepted 1968K 313MS G++ 1415B 2014-07-16 21:19:52 //Accepted 1444K 141MS C++ 1478B 2014-07-16 21:23:23 #include <iostream> #include <cstring> #include <cstdio> #include <cmath> using namespace std; /*===================================================*\ 素数打表,该函数执行后 prim[]数组中存入[2,N]区间内的所有素数(从prim[0]开始存入) isPrime[i] 表示整数 i 是否为素数 函数返回[2,N]之间的素数的个数 \*===================================================*/ const int N = 1000000; bool isPrime[N+10]; int prim[80000]; //要注意保证pirm[]数组足够存储[2,N]之间的素数 int prime(){ int num = 0; memset(isPrime,true,sizeof(isPrime)); isPrime[0] = isPrime[1] = false; for(int i=2 ; i<=N ; i++){ if( isPrime[i] ) prim[num++] = i; for(int j=0 ; j<num ; j++){ if( i*prim[j]>N ) break; isPrime[ i*prim[j] ] = false; if( i%prim[j] == 0 ) break; } } return num; } int n; int main(){ // freopen("in","r",stdin); // freopen("out","w",stdout); int a,b; int numOfPrime = prime(); while( scanf("%d",&n) && n ){ bool findit = false; for(int i=0 ; i<numOfPrime && prim[i]<n ; i++){ a = prim[i]; b = n-a; if( isPrime[b] ){ findit = true; break; } } if( findit ) printf("%d = %d + %d\n",n,a,b ); else printf("Goldbach's conjecture is wrong.\n"); } return 0; }
相关文章推荐
- POJ Goldbach's Conjecture(素数筛~欧拉筛法)
- POJ2262 Goldbach's Conjecture(素数问题)
- POJ 2262 Goldbach's Conjecture (求解素数的一般筛和线性筛)
- UVa 543 Goldbach's Conjecture (素数&哥德巴赫猜想)
- zoj 1951 Goldbach's Conjecture(素数筛选继续水)
- POJ 2262 Goldbach's Conjecture(素数相关)
- hdoj 1397 Goldbach's Conjecture (大数素数打表)
- HDOJ 1397:Goldbach's Conjecture 哈希加筛选法求素数
- (Relax 数论1.13)POJ 2909 Goldbach's Conjecture(欧拉筛法的应用:给出一个偶数,要求在这个偶数的范围内,有几对素数和是等于这个偶数的,注意素数对的不重复性! )
- POJ 2262 Goldbach's Conjecture(素数表)
- POJ2262 Goldbach's Conjecture
- POJ 2262 Goldbach's Conjecture ( 筛选法求素数 )
- POJ 2909 Goldbach's Conjecture(素数表)
- ZOJ 1951 Goldbach's Conjecture(素数打表)
- poj 2262 Goldbach's Conjecture 素数 水题
- poj 2262 Goldbach's Conjecture 【素数筛】
- POJ 2262-Goldbach's Conjecture(素数筛)
- Goldbach's Conjecture(筛选法求素数)
- POJ 2262 Goldbach's Conjecture(素数筛选法)
- HDU 1397 Goldbach's Conjecture(素数判断)