算法笔记 素数 Goldbach’s Conjecture

题目

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 Copy

4
10
16
0
Sample Output Copy

1
2
2

思路

  • 由于2^15=32768仍然在10^5范围内,所以仍然做素数打表
  • 每输入一个n,用i从2到n/2遍历,判断是否i和n-i均为素数表中一员
  • 注意:不考虑1

代码

#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=32770;
int primes[maxn]={
    
    0};
void FindPrime(){
    
    
    primes[1]=1;
    primes[2]=1;
    for(int i=3;i<=pow(2,15);i++){
    
    
        bool flag=true;
        int sqr=sqrt(1.0*i);
        for(int j=2;j<=sqr;j++){
    
    
            if(i%j==0){
    
    
                flag=false;
                break;
            }
        }
        if(flag==true)
            primes[i]=1;
    }
}
int main(){
    
    
    int n=0;
    FindPrime();
    while(scanf("%d",&n)!=EOF){
    
    
        if(n==0)
            break;
        else{
    
    
            int count=0;
            for(int i=2;i<=n/2;i++){
    
    
                if(primes[i]==1&&primes[n-i]==1){
    
    
                    count++;
                    //printf("%d %d %d\n",count,i,n-i);
                }
            }
            printf("%d\n",count);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cindy_00/article/details/108694649
今日推荐