forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp087.java
More file actions
49 lines (38 loc) · 984 Bytes
/
p087.java
File metadata and controls
49 lines (38 loc) · 984 Bytes
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
/*
* Solution to Project Euler problem 87
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.util.HashSet;
import java.util.Set;
public final class p087 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p087().run());
}
private static final int LIMIT = 50000000;
public String run() {
int[] primes = Library.listPrimes(Library.sqrt(LIMIT));
Set<Integer> sums = new HashSet<>();
sums.add(0);
for (int i = 2; i <= 4; i++) {
Set<Integer> newsums = new HashSet<>();
for (int p : primes) {
long q = 1;
for (int j = 0; j < i; j++)
q *= p;
// q = p^i
if (q > LIMIT)
break;
int r = (int)q;
for (int x : sums) {
if (x + r <= LIMIT)
newsums.add(x + r);
}
}
sums = newsums;
}
return Integer.toString(sums.size());
}
}