1099 Sexy Prime (JAVA)

A "sexy prime" is a pair of primes of the form (p, p+6). The reason for this name is because the Latin term for "six" is "sex" (that is, "sexy" in English). (Original excerpt from http://mathworld.wolfram.com/SexyPrimes.html)

Now given an integer, please judge whether it is a sexy prime.

Input format:

Input gives a positive integer N (≤108) in one line.

Output format:

If N is a sexy prime, output on one line Yes, and output another sexy prime paired with N on a second line (if such a number is not unique, output the smaller one). If N is not a sexy prime, output in one line No, then output the smallest sexy prime greater than N in the second line.

Input sample 1:

47

Example-1:">Example 1 of output:

Yes
41

Input sample 2:

21

Sample output 2:

No
23

Code:

import java.io.*;

/**
 * @author yx
 * @date 2022-07-27 17:02
 */
public class Main {
    static PrintWriter out=new PrintWriter(System.out);
    static BufferedReader ins=new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer in=new StreamTokenizer(ins);

    public static void main(String[] args) throws IOException {
        in.nextToken();
        int N=(int) in.nval;
        /*
        讲一下下面这个注释部分为什么会报错,
         */
//          if(isPrime(N)){
//            if(isPrime(N-6)){
//                System.out.println("Yes");
//                System.out.println(N-6);
//                return;
//            }
//            if(isPrime(N+6)){
//                System.out.println("Yes");
//                System.out.println(N+6);
//            }
//        }else {
//            for (int i = N+1;  ; i++) {
//                if(isPrime(i)&&(isPrime(i-6) || isPrime(i+6))){
//                        System.out.println("No");
//                        System.out.println(i);
//                        break;
//                }
//            }
//        }
//    }
        if(isPrime(N) && (isPrime(N-6)||(isPrime(N+6)))){
            if(isPrime(N-6)){
                System.out.println("Yes");
                System.out.println(N-6);
            }else {
                System.out.println("Yes");
                System.out.println(N+6);
            }
        }else {
            for (int i = N+1;  ; i++) {
                if(isPrime(i)&&(isPrime(i-6) || isPrime(i+6))){
                        System.out.println("No");
                        System.out.println(i);
                        break;
                }
            }
        }
    }
    static boolean isPrime(int n){
        if(n<2){//有可能(n-6)为负数,这个地方特判一下
            return false;
        }
        for (int i = 2; i*i<=n ; i++) {
            if(n%i==0)return false;
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/m0_55858611/article/details/126295467