PAT-2019年春季考试-甲级-Sexy Primes

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 (≤1e8).

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

题意:Sexy primes are pairs of primes of the form (p, p+6),被这句题意读崩了,一开始以为是个区间,然后怎么样都过不去就开始枚举题意 。原来题意是先判断n和n-6是不是都是质数,
然后判断n和n+6是不是都是质数(这两种都是Yes的情况),否则就从n+1开始寻找(n,n-6)或者(n,n+6)都是质数的情况(这是No的情况)。

比赛的时候在39min时间过(因为中间自闭了,写第二题去了qwq)
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
int IsPr(int x)
{
    if(x==1 || x==0) return 0;
    int sq=sqrt(x);
    for(int i=2;i<=sq;i++){
        if(x%i==0) return 0;
    }
    return 1;
}
int main()
{
    int n; scanf("%d",&n);

    if(n<5){
        puts("No");
        printf("%d\n",5);
        return 0;
    }
    if(n==5){
        puts("Yes");
        printf("11\n");
        return 0;
    }
    if(IsPr(n) && IsPr(n-6)){
        puts("Yes");
        printf("%d\n",n-6);
        return 0;
    }else if(IsPr(n) && IsPr(n+6)){
         puts("Yes");
         printf("%d\n",n+6);
         return 0;
    }
    else{
        puts("No");
        for(int i=n+1;;i++){
            if(IsPr(i) && IsPr(i-6) || IsPr(i) && IsPr(i+6)){
                printf("%d\n",i);
                return 0;
            }
        }
    }
}

你可能感兴趣的:(pat)