Luogu P1579 Goldbach Conjecture (Upgraded Version) Problem Solution

Luogu P1579 Goldbach Conjecture (Upgraded Version) Problem Solution

This is the first time this Konjac has issued a solution to a problem, and I hope you can correct me.

The original question is shown in the figure

Insert picture description here

Let's analyze this question first. The data intensity of this question is only 20,000, the time limit is 1s, and the memory limit is 125M. Of course, if you want to use general exhaustive methods to judge prime numbers, it will be overtime, so we use the Ericht Sieve method to judge prime numbers.

\\这是埃氏筛的子函数
void prime(int n)
{
	a[0]=a[1]=true;
	for(int i=2;i<=n;i++)  \\如果一个数是质数,那么这个数的倍数就一定都是合数
	if(!a[i])             \\当a[i]为false时说明i为质数
	{
		b[cnt++]=i;
		for(int j=i*i;j<=n;j+=i) \\标记i的倍数为合数
		a[j]=true;
	}
}

Now attach the AC code

#include<bits/stdc++.h> \\万能头大法好
using namespace std;
bool a[20005];
int b[20005];
int cnt=0;
void prime(int n)
{
	a[0]=a[1]=true;
	for(int i=2;i<=n;i++)
	if(!a[i])
	{
		b[cnt++]=i;
		for(int j=i*i;j<=n;j+=i)
		a[j]=true;
	}
}
int main (void)
{
	int n,flag=0;
	scanf("%d",&n);
	prime(n);
	for(int i=0;i<cnt;i++)    \\双重循环进行穷尽
	{
	for(int j=0;j<cnt;j++)
	if(!a[n-b[i]-b[j]]&&n-b[i]-b[j]>0)
	{
		flag=1; \\判断已经找到符合要求的组合
		printf("%d %d %d",b[i],b[j],n-b[i]-b[j]);
		break;
	}
		if(flag) \\如果已经找到符合要求的组合就跳出循环
		break;
	}
}

Guess you like

Origin blog.csdn.net/qq_52758563/article/details/112403773