从键盘输入一个大于6的偶数,把该偶数分解为两个素数(1,2,3视为素数)之和(哥德巴赫猜想)。整数的大小限定在4个字节能表示的范围。用java写
时间: 2024-05-24 16:12:15 浏览: 67
Every even number is equal to the difference of two prime number
实现:
import java.util.Scanner;
public class GoldbachConjecture {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
while (true) {
System.out.print("请输入一个大于6的偶数:");
n = input.nextInt();
if (n > 6 && n % 2 == 0) {
break;
}
System.out.println("输入错误,请重新输入。");
}
boolean flag;
for (int i = 2; i <= n / 2; i++) {
flag = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
flag = false;
break;
}
}
if (flag) {
int k = n - i;
flag = true;
for (int j = 2; j < k; j++) {
if (k % j == 0) {
flag = false;
break;
}
}
if (flag) {
System.out.println(n + " = " + i + " + " + k);
break;
}
}
}
}
}
阅读全文