其他分享
首页 > 其他分享> > 7-156 Sexy Primes (20 分)

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

PAT甲级题量增加

昨天还是155道,现在突增到了168道,,,
image
姥姥真贴心Orz

题解1

一道easy题,卡了大半天,自认为逻辑没错,还以为又是什么边界条件,结果改来改去是maxn设置的太小了Orz
image
image

#include <bits/stdc++.h>

using namespace std;
const int maxn=110000000;
bool prime(int n)
{
    if(n<=1) return false;
    for(int i=2;i*i<=n;i++){
        if(n%i==0) return false;
    }
    return true;
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    int n;
    cin>>n;
    if(prime(n-6)&&prime(n)){
        cout<<"Yes"<<endl;
        cout<<n-6;
    }else if(prime(n)&&prime(n+6)){
        cout<<"Yes"<<endl;
        cout<<n;
    }else{
        cout<<"No"<<endl;
        for(int i=n+1;i<maxn;i++){
            if(prime(i)&&prime(i-6)||prime(i)&&prime(i+6)){
                cout<<i;
                break;
            }
        }
        //break;
    }
    return 0;
}

题解2

#include <bits/stdc++.h>

using namespace std;
const int maxn=100000010;
bool prime(int n)
{
    if(n<=1) return false;
    for(int i=2;i*i<=n;i++){
        if(n%i==0) return false;
    }
    return true;
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    int n;
    cin>>n;
    if(prime(n-6)&&prime(n)){
        cout<<"Yes"<<endl;
        cout<<n-6;
    }else if(prime(n)&&prime(n+6)){
        cout<<"Yes"<<endl;
        cout<<n;
    }else{
        cout<<"No"<<endl;
        while(1){
            n++;
            if(prime(n)&&prime(n-6)||prime(n)&&prime(n+6)){
                cout<<n;
                break;
            }
        }
    }
    return 0;
}

标签:prime,20,int,Sample,sexy,print,Sexy,Primes,Input
来源: https://www.cnblogs.com/moonlight1999/p/15768935.html