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

原文链接: https://www.cnblogs.com/moonlight1999/p/15768935.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    7-156 Sexy Primes (20 分)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/183589

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 上午10:25
下一篇 2023年2月12日 上午10:25

相关推荐