Goldbach conjecture ---------------------------------------- number theory (linear sieve)

The contents of Goldbach's conjecture are as follows:

Any even number greater than 4 can be split into the sum of two odd prime numbers.

E.g:

8 = 3 + 5
20 = 3 + 17 = 7 + 13
42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23
Now, your task is to verify that all even numbers less than one million can satisfy Goth Bach conjecture.

Input format The
input contains multiple sets of data.

Each group of data occupies one line and contains an even number n.

The reading ends with 0.

Output format
For each set of data, the output is of the form n = a + b, where a and b are odd prime numbers.

If there are multiple groups of a and b that satisfy the condition, the group with the largest b−a is output.

If there is no solution, output Goldbach's conjecture is wrong.

Data range
6≤n <106
Sample input:
8
20
42
0
Sample output:
8 = 3 + 5
20 = 3 + 17
42 = 5 + 37

Analysis:
linear sieve template

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+1000;
bool st[N];
int prime[N];
int cnt;
int n;
void init()
{
	memset(st,false,sizeof st);
	for(int i=2;i<=N;i++)
	{
		if(!st[i])
		{
			prime[++cnt]=i;
		}
		for(int j=1;prime[j]<=N/i&&j<=cnt;j++)
		{
			st[prime[j]*i]=true;
			if(i%prime[j]==0) break;
		}
	}
}
int main()
{
	init();
	while(~scanf("%d",&n)&&n!=0)
	{
		int f=0;
		for(int i=2;i<=n/2;i++)
		{
			if((!st[i]&&i%2)&&(!st[n-i]&&(n-i)%2))
			{
				f=1;
				printf("%d = %d + %d\n",n,i,n-i);
				break;
			}
		}
		if(f==0) cout<<"Goldbach's conjecture is wrong."<<endl;
	}
 } 

Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105381235