Prime number II Problem solution (prime number 筛)

Title description

Entering an information and communication pavilion in the Expo Park, visitors will get an unprecedented cutting-edge interactive experience. An information and communication interactive experience show full of creativity and joy will be presented in a new form, starting from the first step of the audience entering the pavilion. It will be inseparable from the handheld terminal, and the surprise of human future dreams will unfold from the palm of the visitor.
In the dream garden in the waiting area, visitors began their wonderful experience journey. Waiting visitors can use mobile phones and other terminals to participate in interactive mini games, and compete with the virtual character Kr. Kong in the dream theater. When an integer X appears on the screen, if you can issue the prime answer closest to it faster than Kr. Kong, you will get an unexpected gift.
For example: when 22 appears on the screen, your answer should be 23; when 8 appears on the screen, your answer should be 7; if X itself is a prime number, answer X; if there are two prime numbers closest to X, then The answer is greater than its prime.

enter

The first line, a positive integer n, represents the number of integers to be guessed; the
next n lines, each line has a positive integer X.

Output

The output has n rows, and each row has an integer, which represents the prime number closest to the corresponding X.

Sample input

4
22
5
18
8

Sample output

23
5
19
7
Tip: For 100% data: n<=1000000, X<=10000000.

The prime number sieve processed all the prime numbers in 1e7, and the prime numbers were processed, and it was found that the interval between two adjacent prime numbers in 1e7 would not exceed 200. If n is a prime number, then output itself, if n is not a prime number, search in both directions up and down, and output directly when a prime number is found.

#include<bits/stdc++.h>
#pragma GCC optimize(2)
#define ll long long
using namespace std;
int _,n,f[10000010];
int main(){
    
    
	f[1]=1;
	for(int i=2;i<=10000000;i++) if(!f[i])
		for(int j=2*i;j<=10000000;j+=i) f[j]=1;
	scanf("%d",&_);
	while(_--){
    
    
		scanf("%d",&n);
		if(!f[n]) printf("%d\n",n);
		else if(n&1)
			for(int i=2;i<=1000;i+=2){
    
    
				if(!f[n+i]&&n+i<=10000000){
    
    
					printf("%d\n",n+i);
					break;
				}
				else if(!f[n-i]&&n-i>=2){
    
    
					printf("%d\n",n-i);
					break;
				}
			}
		else
			for(int i=1;i<=1000;i+=2){
    
    
				if(!f[n+i]&&n+i<=10000000){
    
    
					printf("%d\n",n+i);
					break;
				}
				else if(!f[n-i]&&n-i>=2){
    
    
					printf("%d\n",n-i);
					break;
				}
			}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_50808324/article/details/112787778