PAT 甲级 2019年春季三月份 7-1 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 (≤108).

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
#include <iostream>
#include <cstdio>
using namespace std;
int N;
bool flag=false;
bool isPrime(int a)
{
    if(a<=1)
        return false;
    for(int i=2;i*i<=a;i++)
        if(a%i==0)
            return false;
    return true;
}
int isSex(int a)
{
    bool f=isPrime(a)&&isPrime(a-6);
    if(f)
       return a-6;
    f=isPrime(a)&&isPrime(a+6);
    if(f)
       return a+6;
    return -1; //未成功
}
int main()
{

    cin>>N;
    int a=isSex(N);
    if( a!=-1 )
    {
        printf("Yes\n%d\n",a);
        return 0;
    }
    N++;
    while( true )
    {
        if( isSex(N)!=-1 )
        {
            printf("No\n%d\n",N);
            return 0;
        }
        N++;
    }
    return 0;
}

发布了174 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41173604/article/details/100608720
今日推荐