1099. Sexy Primes (20 points)

"Sensual prime number" refers to a pair of prime numbers of the form (p, p+6). The reason for this name is that "six" is called "sex" in Latin (that is, "sexy" in English). (Original excerpt from http://mathworld.wolfram.com/SexyPrimes.html)

Now given an integer, please judge whether it is a sexy prime number.

Input format:

The input gives a positive integer N (≤108) in one line.

Output format:

If N is a sexy prime number, output it on one line Yes, and output another sexy prime number paired with N on the second line (if such number is not unique, output the smaller one). If N is not a sexy prime number, output it in one line No, and then output the smallest sexy prime number greater than N in the second line.

Input sample 1:

47

Sample-1: "> Sample-1: "> Output Sample 1:

Yes
41

Input sample 2:

21

Output sample 2:

No
23

The point to note is that when judging a prime number, it should be noted that the smallest prime number is 2, and anything less than 2 is not a prime number. In addition, when N is not a sexy prime number, when looking for a sexy prime number larger than N, the number M found may be the larger one in the sexy prime number pair, so isPrime(i-6) should also be considered

#include<cstdio>
#include<cmath> 
#include<iostream>
using namespace std;
bool isPrime(int num);
int main(){
	int N;
	cin>>N;
	if(isPrime(N) && isPrime(N-6))
		cout<<"Yes"<<endl<<N-6<<endl;
	else if(isPrime(N) && isPrime(N+6))
		cout<<"Yes"<<endl<<N+6<<endl;
	else{
		for(int i=N+1;;i++){
			//i本身是质数,且i-6 或者 i+6 也是质数 
			if(isPrime(i)&&(isPrime(i+6)||isPrime(i-6))){
				cout<<"No"<<endl<<i<<endl;
				break;
			}
				
		}
	}	
	return 0;
}

bool isPrime(int num){
	if(num<2)
		return false;
	int n=sqrt(num);
	for(int i=2;i<=n;i++)
		if(num%i==0)
			return false;
	return true;
}

Guess you like

Origin blog.csdn.net/qq_16382227/article/details/124035005