This is a project Euler Problem #50. Here is my solution with the problem.
/*
* The prime 41, can be written as the sum of six consecutive primes: 41 = 2
* + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that
* adds to a prime below one-hundred. The longest sum of consecutive primes
* below one-thousand that adds to a prime, contains 21 terms, and is equal
* to 953. Which prime, below one-million, can be written as the sum of the
* most consecutive primes?
*/
public static int get50() {
int max = 21;
int prime_max = 953;
ArrayList<Integer> primes = Helper.getPrimes(1000000);
for (int len = 21; len <= primes.size(); len += 2) {
long sum = 0;
if (primes.get(len - 1) > 1E6) {
break;
}
if (sum > 1E6) {
return prime_max;
}
for (int k = 0; len + k - 1 < primes.size(); k++) {
if (k == 0) {
for (int i = 0; i < len; i++) {
sum += primes.get(i);
}
} else {
sum += primes.get(len + k - 1) - primes.get(k - 1);
}
if (primes.get(len + k - 1) > 1E6 || sum > 1E6) {
break;
}
if (Helper.isPrime((int) sum)) {
if (len > max) {
max = len;
prime_max = (int) sum;
}
break;
}
}
}
return prime_max;
}
Some things I wish to improve:
- Time (currently over 40 seconds,
Answer is 997651, Time taken 43.762743956 seconds
) - If possible && If reduces time Then using the new Java 8 methods.This would help me learn it too.
Helper.getPrimes(1000000)
returns all primes under1000000
? \$\endgroup\$Helper.getPrimes(1000000)
take on its own? \$\endgroup\$Time taken 0.101968274 seconds
\$\endgroup\$