-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem046.java
More file actions
47 lines (43 loc) · 1.07 KB
/
problem046.java
File metadata and controls
47 lines (43 loc) · 1.07 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
package project_beuler;
public class problem046 {
// 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?
public static void main(String[] args) {
// TODO Auto-generated method stub
String output = "";
for(int n = 9; output.length() == 0; n+=2) {
if(Interface.isPrime(n)) continue;
int prime = 2; double squared = 1;
while(prime + 2*1 <= n){
squared = Math.sqrt((n - prime)/2.0);
if( isInteger( squared ) )
break;
prime = nextPrime(prime);
}
if( !isInteger(squared) )
output = n+"";
}
System.out.println(output);
}
public static int nextPrime(int n) {
do {
n++;
}while(!Interface.isPrime(n));
return n;
}
public static boolean isInteger(double n) {
return n == (int) n;
}
}