Goldbach's Conjecture

题目描述:

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.

输入:

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. 

输出:

Each output line should contain an integer number. No other characters should appear in the output.

样例输入:

4
10
16
0

样例输出:

1
2
2

链接:

http://codeup.cn/problem.php?cid=100000591&pid=2

翻译:

哥德巴赫猜想:对于任何大于或等于4的偶数n,至少存在一对素数p1和p2,使n = p1 + p2。

这一猜想既未被证实,也未被拒绝。没有人确定这个猜想是否正确。但是,对于给定的偶数,如果有的话,可以找到这样一对质数。这里的问题是编写一个程序,报告一个给定偶数满足猜想条件的所有质数对的数量。

给出一个偶数序列作为输入。对应于每个数字,程序应该输出上面提到的对的数量。注意,我们感兴趣的是本质上不同的对的数量,因此不应该将(p1, p2)和(p2, p1)单独计算为两对不同的对。

在每个输入行中给出一个整数。你可以假设每个整数都是偶数,大于等于4小于2^15。输入的结束用数字0表示。

每个输出行应该包含一个整数。输出中不应该出现其他字符。

思路:

首先使用素数筛将素数保存到数组中,然后遍历数组查找有无满足哥德巴赫猜想的两个值

代码:

#include<iostream>
using namespace std;
const int maxn=100000;
bool hashTable[maxn]={false};
int prime[maxn];
int pNum=0;

void Find_Prime(){//素数表 
     for(int i=2;i<=maxn;i++){
         if(hashTable[i]==false){
             prime[pNum++]=i;
             for(int j=2*i;j<=maxn;j=j+i){
                 hashTable[j]=true;
             }
         }
     }
}

int main(){
    int k;
    Find_Prime();
    while(cin>>k){
        if(k==0){
            exit(0);
        }
        else{
            int count=0;
            for(int j=k;j>0;j--){
                
                if(prime[j]>k){
                    continue;
                }
                
                for(int i=0;i<=j;i++){
                    if(prime[i]+prime[j]==k){
                        count++;
                        
                    }
                }
            }
            cout<<count<<endl;
        }
    }
    return 0;
}

结果:

还有没想到的地方

原文地址:https://www.cnblogs.com/ak918xp/p/13533767.html