PAT乙级-1007 素数对猜想

让我们定义d**n为:d**n=p**n+1−p**n,其中p**i是第i个素数。显然有d1=1,且对于n>1有d**n是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<105),请计算不超过N的满足猜想的素数对的个数。

输入格式:

输入在一行给出正整数N

输出格式:

在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:

20
结尾无空行

输出样例:

4
结尾无空行

注意事项

本题的最后一个测试用例的数值过大,直接用暴力枚举的方式会超时

参考 https://blog.csdn.net/qq_43886120/article/details/109119025 得到解决方法

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(test(n));
    }

    public static int test(int n){
        List<Integer> list = new ArrayList<>();
        int sum = 0;

        for(int i = 2; i <= n; i++){
            boolean x = true;
            for(int j = 2; j < Math.sqrt(i) + 1; j++){
                if(i % j == 0){
                    x = false;
                    break;
                }
            }
            if(x) list.add(i);
        }

        for(int i = 0; i < list.size() - 1; i++){
            if(list.get(i + 1) - list.get(i) == 2)
                sum++;
        }
        return sum;
    }
}

posted @ 2021-11-19 16:32  黯渊  阅读(22)  评论(0编辑  收藏  举报