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, 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

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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM