C++ newoj Goldbach conjecture

Goldbach Conjecture

Any even number greater than 2 can be written as the sum of two prime numbers

original title

1081: Goldbach's Conjecture

Memory limit: 256 MB
Time limit: 1 S

Title Description
Input a positive integer n not less than 6, split it into the sum of three prime numbers, and output any solution.
Input format
There are multiple sets of test data in the input, and each set of test data input line contains a positive integer n (6<=n<=20000)
Output format
For each set of test data, output three prime numbers, separated by spaces, and there is no space at the end of the line.
Input example
6
7
8
Output example
2 2 2
2 2 3
2 3 3
Classification label Enumeration of basic questions

If it is the original Goldbach's conjecture, it is directly violently split into two numbers, and the method for three numbers is similar

1. First judge whether the input is an odd number or an even number
. 2. Odd number: Subtract 3, and the result is still an even number. Transform into "Goldbach's Conjecture: Any even number greater than 2 can be written as the sum of two prime numbers"
3. It is an even number: Subtract 2, and the result is still an even number, which is also transformed into "Goldbach's Conjecture: Any even number greater than 2 can be written as the sum of two prime numbers"

C++ code

#include<iostream>
#include<cmath>
using namespace std;
bool is_prime(int n)
{
    
    
    if( n==2 || n==3 ) return true;
    for( int i=2;i<=sqrt(n);i++ )
    {
    
    
        if( n%i==0 ) return false;
    }
    return true;
}
void out(int ans1,int n)
{
    
    
    for( int i=2;i<n;i++ )
    {
    
    
        if( !is_prime(i) ) continue;
        for( int j=n-i;j>=2;j-- )
        {
    
    
            if( is_prime(j) )
            {
    
    
                if( (i+j)==n )
                {
    
    
                    cout<<ans1<<" "<<i<<" "<<j<<endl;
                    return ;
                }
                if( (ans1+i+j)<n ) break;
            }
            else continue;
        }

    }
}
int main()
{
    
    
    /*
    当输入数据为偶数时:
    对输入数据减去2,剩下的值依然是个偶数,然后再通过暴力把剩下的两个素数求出来;

    当输入数据为奇数时:
    对输入数据减去3,剩下的值便是偶数,仍是通过暴力把剩下的两个素数求出来;
    */

    //哥德巴赫猜想 任一大于2的偶数都可写成两个素数之和
    int n;
    while(cin>>n)//6<=n<=20000
    {
    
    
        int ans1;
        if( n%2==0 )
        {
    
    
            ans1=2;
            n -= ans1;
        }
        else
        {
    
    
            ans1=3;
            n -= ans1;
        }
        out(ans1,n);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_47700137/article/details/129237316