您的位置:首页 > 其它

HDU1397-哥德巴赫猜想

2014-01-28 02:57 176 查看


Goldbach's Conjecture

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 4230    Accepted Submission(s): 1571


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

Source

Asia 1998, Tokyo (Japan)

 
思路:
  哥德巴赫猜想:任何一个>=4的偶数都可以表示成两个素数之和。给出一个>=4的偶数求出满足条件的素数对。
思路,就是暴力打出一张素数表,然后,首尾蛮力搜索。
#include <stdio.h>
#include <iostream>
using namespace std;

//Dynamic Programming find primes
//first step : find Status Prime[0] = 2,
//second step: find the Transfer formula,
//when the number A[i] can % prime[0...i] == 0,
//it's not a prime,else it is a prime.

int prime[50000];
int pLen;

void SetPrime()//dp set prime
{
int i,j;
pLen = 1;
bool isPrime;
prime[0] = 2;
for (i=3; i<50000; i += 2)
{
isPrime = true;
for(j=0; j<pLen; ++j)
{
if (i%prime[j] == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
prime[pLen++] = i;
}
}
int FindPrimePair(int n)
{
int i = 0,j = pLen-1,sum = 0;
for(; i <= j;)
{
if (prime[i]+prime[j] == n)
{
++i;
--j;
++sum;
}
else if (prime[i]+prime[j] > n)
--j;
else
++i;
}
return sum;
}
int main()
{
int n;
SetPrime();
while (cin >> n && n != 0)
{
cout << FindPrimePair(n) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 算法