题目:

让我们定义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

答案:

Java

public class Suanfa02 {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        int count = 0, i, j;
        int p = 2;
        for (i = 3; i <= n; i++) {
            for (j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0 )
                    break;
            }
            if (j > Math.sqrt(i)) {
                if (i - p == 2) {
                    count++;
                }
                p = i;
            }
        }
        System.out.print(count);
    }
}