码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2021-02-20 11:45:24      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:http   iostream   tin   red   mes   The   spec   mat   输出   

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;
}

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

标签:http   iostream   tin   red   mes   The   spec   mat   输出   

原文地址:https://www.cnblogs.com/coderJ-one/p/14413446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!