- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
69 lines (60 loc) · 1.56 KB
/
Copy pathMain.java
File metadata and controls
69 lines (60 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
importjava.util.ArrayList;
importjava.util.List;
/*
@author: mc-es
Problem 46
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
Answer: 5777
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
intresult = findSmallestCounterexample();
System.out.println("The first number where the hypothesis is wrong is: " + result);
}
publicstaticbooleanisPrime(intn) {
if (n < 2) {
returnfalse;
}
for (inti = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
returnfalse;
}
}
returntrue;
}
publicstaticbooleancanBeExpressed(intn, List<Integer> primes) {
for (intp : primes) {
if (p >= n) {
break;
}
intkSquared = (n - p) / 2;
intk = (int) Math.sqrt(kSquared);
if (k * k == kSquared) {
returntrue;
}
}
returnfalse;
}
publicstaticintfindSmallestCounterexample() {
List<Integer> primes = newArrayList<>();
intn = 3;
while (true) {
if (isPrime(n)) {
primes.add(n);
} else {
if (!canBeExpressed(n, primes)) {
returnn;
}
}
n += 2;
}
}
}