1007. 素数对猜想 (20)

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

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

输入格式:每个测试输入包含1个测试用例,给出正整数N。

输出格式:每个测试用例的输出占一行,不超过N的满足猜想的素数对的个数。

输入样例:

20

输出样例:

4
 1 import java.util.*;
 2 
 3 public class Main {
 4     private static Map<Integer,Boolean> map=new HashMap<Integer,Boolean>();
 5     private static boolean isPrime(int num){
 6         if(map.get(num)!=null)return map.get(num);
 7         for(int i=2;i<=Math.sqrt(num);i++){
 8             if(num%i==0) {
 9                 map.put(num,false);
10                 return false;
11             }
12         }
13         map.put(num,true);
14         return true;
15     }
16 
17 
18     public static void main(String[] args) {
19         Scanner in = new Scanner(System.in);
20         int size=0;
21         while (in.hasNext()) {
22             int N=in.nextInt();
23             int count=0;
24             for(int i=5;i<=N;i+=2){
25                if(isPrime(i)&&isPrime(i-2)){
26                    count++;
27                }
28             }
29             System.out.println(count);
30 
31         }
32     }
33 }
原文地址:https://www.cnblogs.com/BJUT-2010/p/5554240.html