PAT 2019-3 7-1 Sexy Primes
Description:
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 (≤).
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, printNo
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
Keys:
- 素数
Attention:
- 这几次很爱考素数,奶一口欧拉算法,9月份考试能不能中
Code:
1 /* 2 SP数,P和P+6都是素数 3 给定一个正整数,判断N是否为SP数,打印与他配对的另一个素数(如果不唯一,输出较小的一个 4 如果N不是SP数,打印大于N的最小SP数 5 6 1,判断i-6是否大于n 7 2,n-6可能小于0, 8 */ 9 #include<cstdio> 10 11 bool IsPrime(long long n) 12 { 13 if(n <= 1) 14 return false; 15 for(long long i=2; i*i<=n; i++) 16 if(n%i == 0) 17 return false; 18 return true; 19 } 20 21 int main() 22 { 23 #ifdef ONLINE_JUDGE 24 #else 25 freopen("Test.txt", "r", stdin); 26 #endif // ONLINE_JUDEG 27 28 int n; 29 scanf("%d",&n); 30 if(IsPrime(n-6) && IsPrime(n)) 31 printf("Yes\n%d", n-6); 32 else if(IsPrime(n) && IsPrime(n+6)) 33 printf("Yes\n%d", n+6); 34 else 35 { 36 for(int i=n+1; i<1e9; i++) 37 if(IsPrime(i-6) && IsPrime(i)) 38 { 39 printf("No\n%d", i-6>n?i-6:i); 40 break; 41 } 42 } 43 44 return 0; 45 }