package december;
import java.util.Scanner;
/*
* 哥德巴赫猜想:任何大于2的的偶数,都可以表示为两个素数之和。
* 素数:大于1的自然数中,除一和自身外没办法被其他自然数整除的数
* 要求验证:给出范围验证哥德巴赫猜想,
* 思想:穷举法判断,只要有一个偶数不满足,它就是不成立的!
*/
public class Guss_5 {
// 判断是否为素数
public static boolean isPrime(int i) {
boolean flag = true;
if (i == 1)
flag = false;
for (int n = 2; n <= i - 1; n++) {
if (i % n == 0) {
flag = false;
break;
}
}
return flag;
}
// 近似验证哥德巴赫猜想
public static boolean isGoldbach(int a) {
boolean flag = false;
//对于任何正偶数a都有 a = 1+(a-1), a = 2+(a-2)... a = m/2 +m/2,两段都是一样的,只是前后相加顺序不同,所以i <= a/2次循环就够了
for (int i = 1; i <= (a >> 1); i++) {
if (isPrime(i) && isPrime(a - i)) {
System.out.printf("%3d=%3d+%3d\t\t", a, i, (a - i));
flag = true;
break;
}
}
return flag;
}
// 测试范围是否符合哥德巴赫猜想
public static boolean test(int low, int height) {
boolean flag = true;
int j = 0;
for (int i = low; i <= height; i++) {
if (i % 2 == 0 && i > 2){
if (isGoldbach(i)) {
j++;
if (j%5 == 0) {
System.out.println();
}
} else {
flag = false;
break;
}
}
}
return flag;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入low:");
int low = sc.nextInt();
System.out.println("请输入height::");
int height = sc.nextInt();
System.out.println("下面开始测试"+low+"+"+height+"之间的数字:");
if (test(low, height)) {
System.out.println("哥德巴赫猜想成立!!");
} else {
System.out.println("哥德巴赫猜想不成立!");
}
sc.close();
}
}
运行截图如下: