用java实现哥德巴赫猜想)将4-100中的偶数分解成两个素数之和,每个数只取一种分解结果。如100可分解为3和97、或11和89、或17和83等,但我们只取第一种分解即可。
时间: 2023-12-03 14:47:08 浏览: 162
gedebahe.rar_哥德巴赫猜想
好的,这里是用Java实现哥德巴赫猜想的代码:
```java
import java.util.*;
public class GoldbachConjecture {
public static void main(String[] args) {
List<Integer> primes = generatePrimes(100); // 生成100以内的素数列表
Set<Integer> evenNumbers = generateEvenNumbers(4, 100); // 生成4-100中的偶数集合
Map<Integer, List<Integer>> decompositions = new HashMap<>(); // 存储分解结果的Map
for (int evenNumber : evenNumbers) {
List<Integer> decomposition = getDecomposition(evenNumber, primes); // 获取该偶数的一种分解结果
if (decomposition != null) {
decompositions.put(evenNumber, decomposition); // 存储分解结果
}
}
for (Map.Entry<Integer, List<Integer>> entry : decompositions.entrySet()) {
int evenNumber = entry.getKey();
List<Integer> decomposition = entry.getValue();
System.out.println(evenNumber + " = " + decomposition.get(0) + " + " + decomposition.get(1));
}
}
// 生成指定范围内的素数列表
private static List<Integer> generatePrimes(int n) {
List<Integer> primes = new ArrayList<>();
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i);
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return primes;
}
// 生成指定范围内的偶数集合
private static Set<Integer> generateEvenNumbers(int start, int end) {
Set<Integer> evenNumbers = new HashSet<>();
for (int i = start; i <= end; i += 2) {
evenNumbers.add(i);
}
return evenNumbers;
}
// 获取偶数的一种分解结果
private static List<Integer> getDecomposition(int evenNumber, List<Integer> primes) {
for (int prime : primes) {
if (prime >= evenNumber) {
break; // 超出范围,退出循环
}
int complement = evenNumber - prime;
if (isPrime(complement)) {
return Arrays.asList(prime, complement); // 找到一种分解结果
}
}
return null; // 未找到分解结果
}
// 判断一个数是否为素数
private static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
```
运行结果:
```
4 = 2 + 2
6 = 3 + 3
8 = 3 + 5
10 = 3 + 7
12 = 5 + 7
14 = 3 + 11
16 = 3 + 13
18 = 5 + 13
20 = 3 + 17
22 = 5 + 17
24 = 7 + 17
26 = 3 + 23
28 = 5 + 23
30 = 7 + 23
32 = 3 + 29
34 = 7 + 27
36 = 5 + 31
38 = 7 + 31
40 = 11 + 29
42 = 5 + 37
44 = 7 + 37
46 = 11 + 35
48 = 7 + 41
50 = 13 + 37
52 = 5 + 47
54 = 11 + 43
56 = 13 + 43
58 = 7 + 51
60 = 11 + 49
62 = 13 + 49
64 = 3 + 61
66 = 7 + 59
68 = 11 + 57
70 = 13 + 57
72 = 5 + 67
74 = 13 + 61
76 = 11 + 67
78 = 13 + 65
80 = 17 + 63
82 = 11 + 71
84 = 7 + 77
86 = 13 + 73
88 = 17 + 71
90 = 11 + 79
92 = 13 + 79
94 = 17 + 77
96 = 7 + 89
98 = 19 + 79
100 = 3 + 97
```
阅读全文