Finding the prime number (counting the 2019 Lanqiao Cup Provincial Tournament Group B Simulation Tournament 1)

topic

  	一天蒜头君猜想,是不是所有的偶数(除了 22),都可以用两个质数相加得到呢?于是聪明的蒜头君就找你来验证了。

	输入格式
	第一行输入一个整数 t 表示测试组数。

	接下来 t 行,每行一个整数 n。

	输出格式
	输出两个整数,因为答案可能有多个,所有要求输出的这两个整数是所有答案中字典序最小的。

	数据范围
	对于 30% 的数据 1 ≤ t ≤ 10^3。
	对于 60% 的数据 1 ≤ t ≤ 10^5。
	对于 100% 的数据 1 ≤ 10^6, 4 ≤ n ≤ 10^6 ,n 为偶数。

	样例输入
	3
	4
	8
	20

	样例输出
	2 2
	3 5
	3 17

Due to the large data in this question, we can consider using the method of linear screening of prime numbers to store them in the table, and then look up the table at the end.

The codes for metering and depositing are as follows:

void data()
{
    
    
	ms(a),ms(b);
	for(int i=1;i<=1e6;i++) 
		for(int j=i;j<=1e6;j+=i)
			a[j]++;
			
	for(int i=1;i<=1e6;i++)
		if(a[i]==2){
    
    
			b[l++]=i;
		}
}

The requirement of the question is to find two prime numbers that add up to n. We might as well use the method of enumeration, first enumerate a prime number i, and look up in the table whether n-i are also prime numbers, and if they are satisfied at the same time, it conforms Claim.

It should be noted that since there may be multiple sets of answers, the required lexicographic order is the smallest (that is, the smallest number), so the case we finally output should be the set of use cases with the smallest i when meeting the requirements.

The complete code is as follows:

#include <bits/stdc++.h>
#define ms(a) memset(a,0,sizeof(a))
using namespace std;

int a[1000009];
int b[1000009];
int l=0;

void data()
{
    
    
	ms(a),ms(b);
	for(int i=1;i<=1e6;i++)
		for(int j=i;j<=1e6;j+=i)
			a[j]++;
	
	for(int i=1;i<=1e6;i++)
		if(a[i]==2){
    
    
			b[l++]=i;
		}
			
}

int main()
{
    
    
	l=0;
	data();
	int t,n;
	scanf("%d",&t);
	while(t--)
	{
    
    
		scanf("%d",&n);
		int i=0;
		int x,y;
		while(i<l&&b[i]<=n)
		{
    
    
			x=b[i];
			y=n-x;
			if(a[y]==2) 
				break;
			i++;
		}
		printf("%d %d\n",x,y);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/laysan/article/details/113577455