Lucky number of tube (linear sieve)

Insert picture description here
Idea: This question can also be violent, but I first filter out prime numbers, and then determine whether n is a prime number for each inquiry, and if not, find a prime number smaller and larger than it. Finally found the nearest one.

#include <bits/stdc++.h>
using namespace std;
int prime[100010];
void is_prime(int x){
    
    
    for(int i=2;i<=sqrt(x);i++){
    
    
        if(prime[i]==0){
    
    
            for(int j=i*i;j<=x;j+=i){
    
    
                prime[j] = 1;
            }
        }
    }
}

int main()
{
    
    
    int t; cin>>t;
    is_prime(100000);
    while(t--){
    
    
        int n; cin>>n;
        if(prime[n]==0) cout<<"YES"<<endl;
        else {
    
    
            int cnt1=0,cnt2=0;
            for(int i=n;;i++){
    
    
                if(prime[i]==0){
    
    
                    cnt1 = i;
                    break;
                }
            }
            for(int i=n;;i--){
    
    
                if(prime[i]==0){
    
    
                    cnt2 = i;
                    break;
                }
            }
            int ans = min(abs(n-cnt1),abs(n-cnt2));
            cout<<ans<<endl;
        }
    }
    return 0;
}

At the beginning, the array was opened at 10005wa, and it was passed by increasing it later. Be sure to pay attention to the range next time.

Guess you like

Origin blog.csdn.net/qq_43811879/article/details/109607089