-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler50.java
More file actions
70 lines (49 loc) · 1.32 KB
/
euler50.java
File metadata and controls
70 lines (49 loc) · 1.32 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
70
public class ConsecutivePrimeSum {
static final int N = 1000000;
// Largest Prime under N
static final int largePrime = 999983;
static boolean primes[] = new boolean[N+1];
// Sieve Marks off all multiples of i
static void findPrimes() {
for(int i = 0; i <= N; i++)
primes[i] = true;
for (int i = 2; i <= Math.sqrt(N); i++)
if (primes[i])
for (int j = 2*i; j <= N; j+=i)
primes[j] = false;
}
static boolean isPrime(int num) {
if(num > N)
return false;
return primes[num];
}
public static void main(String[] args) {
findPrimes();
int prevCount = 0, sum = 0, count = 0, answer = 0;
for(int i = 2; i <= N; i++) {
// The next prime sum to attempt
if(primes[i]) {
// Start the sum at the newly found prime and reset the count
sum = i;
count = 0;
// Begin adding up primes
for(int j = i + 1; sum + j <= largePrime; j++) {
// The next prime to add
if(primes[j]) {
sum += j;
count++;
// Check to see if the sum is prime
if(isPrime(sum)) {
// If the sum is prime then lets see if the count > then our previous best
if(count > prevCount) {
prevCount = count;
answer = sum;
}
}
}
}
}
}
System.out.println(answer);
}
}