其他分享
首页 > 其他分享> > 2019年春季PAT 7-1 Sexy Primes (20 分)

2019年春季PAT 7-1 Sexy Primes (20 分)

作者:互联网

Sexy primes are pairs of primes of the form (p, p+6), so-named since "sex" is the Latin word for "six". (Quoted from http://mathworld.wolfram.com/SexyPrimes.html)

Now given an integer, you are supposed to tell if it is a sexy prime.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (≤10^8​​).

Output Specification:

For each case, print in a line Yes if N is a sexy prime, then print in the next line the other sexy prime paired with N (if the answer is not unique, output the smaller number). Or if N is not a sexy prime, print No instead, then print in the next line the smallest sexy prime which is larger than N.

Sample Input 1:

47

Sample Output 1:

Yes
41

Sample Input 2:

21

Sample Output 2:

No
23

实现思路:
题意就是
1.给一个数P,若p-6和p都是质数则输出p-6,若有一个不是则若是p+6和p都是质数则输出p+6
2.若是都不是的话寻找一个比p大的数满足条件1的数

AC代码:

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int x) {
	if(x<=1) return false;
	int sqr=sqrt(1.0*x);
	for(int i=2; i<=sqr; i++) {
		if(x%i==0) return false;
	}
	return true;
}

int main() {
	int x;
	cin>>x;
	if((isPrime(x)&&isPrime(x-6))) {
		printf("Yes\n");
		printf("%d",x-6);
	} else if(isPrime(x)&&isPrime(x+6)) {
		printf("Yes\n");
		printf("%d",x+6);
	} else {
		printf("No\n");
		while(1) {
			x++;
			if(isPrime(x)&&(isPrime(x+6)||isPrime(x-6))) break;
		}
		printf("%d",x);
	}
	return 0;
}

标签:prime,sexy,20,2019,printf,print,Sexy,isPrime,Yes
来源: https://www.cnblogs.com/coderJ-one/p/14413446.html