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)html
Now given an integer, you are supposed to tell if it is a sexy prime.算法
Each input file contains one test case. Each case gives a positive integer $N (≤10^8)$.函數
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.spa
47
Yes 41
21
No 23
時間限制 | 內存限制 |
---|---|
400 ms | 64 MB |
一個數x是「sexy prime」指的是x是質數且x-6或x+6也是質數。給出一個數,判斷這個數是否是「sexy prime」,若是是的話輸出與這個數配對的另外一個「sexy prime」,若是有多個就輸出小的那個(也就是x-6),若是不是就輸出最小的比這個數大的「sexy prime」。code
使用isPrime函數判斷一個數N是否爲素數,而後對於輸入的數字N,首先判斷N和N-6是否爲素數,若是是,輸出Yes和N-6,不然判斷N和N+6是否爲素數,若是是,輸出Yes和N+6,若是都不是,說明N不是sexy prime,輸出No,而後從N+1開始遍歷每個數字i,判斷i和i-6是否爲素數,若是是輸出i並結束程序,不然判斷i和i+6是否爲素數,若是是輸出i並結束程序。orm
bool isPrime(int N){ if(N<=1) return false; int sqrtn = (int)sqrt(N*1.0); for (int i = 2; i <= sqrtn; ++i) { if(N%i==0) return false; } return true; }
#include<cstdio> #include <cmath> using namespace std; bool isPrime(int N){ if(N<=1) return false; int sqrtn = (int)sqrt(N*1.0); for (int i = 2; i <= sqrtn; ++i) { if(N%i==0) return false; } return true; } int main(){ int N; scanf("%d",&N); if(isPrime(N)&&isPrime(N-6)){ // N是sexy prime,找到僅次於N的sexy prime printf("Yes\n%d",N-6); } else if(isPrime(N)&&isPrime(N+6)){ printf("Yes\n%d",N+6); } else { // N不是sexy prime,找到僅大於N的sexy prime printf("No\n"); for (int i = N+1; ; ++i) { if(isPrime(i)&&isPrime(i-6)){ printf("%d",i); break; } if(isPrime(i)&&isPrime(i+6)){ printf("%d",i); break; } } } return 0; }