zoj 1951 Goldbach's Conjecture

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=951

 

由于以前做过类似的题目,所以马上AC了

思路是建一个素数表,这样会加快程序的运行,不会出现TLE的状况.

建素数表的代码:

const int SIZE = 1000000; int prime[SIZE] = {0}; for(i = 2; i != SIZE / 2; ++i) { j = 2 * i; while(j < SIZE) { prime[j] = 1; j += i; } }

本题特别要注意的几点:

1. cin 和 cout 的速度比scanf 和 printf慢很多,应该使用后者,不然会出现TLE

2.题目中有一句话 where a and b are odd primes 所以应该将prime[2] = 1;

 

贴上代码:

/* * 1951.cpp * * Created on: Apr 6, 2010 * Author: wyy * the second example showing that cin or cout is slower than scanf and printf. */ #include<iostream> using namespace std; int main() { //freopen("input.txt", "r", stdin); const int SIZE = 1000000; int prime[SIZE] = {0}; prime[2] = 1; int i, j; for(i = 2; i != SIZE / 2; ++i) { j = 2 * i; while(j < SIZE) { prime[j] = 1; j += i; } } int k; while(scanf("%d", &k) && k) { for( i = 3; i != k; i += 2) { if( !prime[i] && !prime[k - i] ) { printf("%d = %d + %d/n", k, i, k - i); break; } } if(i == k) cout << "Goldbach's conjecture is wrong." << endl; } //fclose(stdin); return 0; }

你可能感兴趣的:(zoj 1951 Goldbach's Conjecture)