您的位置:首页 > 编程语言 > Go语言

zoj 1951 Goldbach's Conjecture

2010-04-06 11:55 417 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: