1007 素数对猜想 (20 分)
让我们定义dn为:dn=pn+1−pn,其中pi是第i个素数。显然有d1=1,且对于n>1有dn是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。
现给定任意正整数N
(<105),请计算不超过N
的满足猜想的素数对的个数。
输入格式:
输入在一行给出正整数N
。
输出格式:
在一行中输出不超过N
的满足猜想的素数对的个数。
输入样例:
20
输出样例:
4
- 测试点 5 运行时长问题 在判定素数是只用判定i判定倒sqrt(n)即可,
- 测试点5 答案错误 可能是其他方法中的int类型数值过大, 可用 99999测试 正确答案是 1224
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
while (n > 3) {
if ((Prime(n)) && (Prime(n - 2))) {
count++;
}
n--;
}
System.out.println(count);
}
private static boolean Prime(int n) {
for(int i=2; i <= Math.sqrt(n); i++){
if(n%i==0)
return false;
}
return true;
}
}