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?
Solution:
997651
Code:
The solution may include methods that will be found here: Library.java .
public interface EulerSolution{
public String run();
}
/*
* Solution to Project Euler problem 50
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p050 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p050().run());
}
private static final int LIMIT = Library.pow(10, 6);
public String run() {
boolean[] isPrime = Library.listPrimality(LIMIT);
int[] primes = Library.listPrimes(LIMIT);
long maxSum = 0;
int maxRun = -1;
for (int i = 0; i < primes.length; i++) { // For each index of a starting prime number
int sum = 0;
for (int j = i; j < primes.length; j++) { // For each end index (inclusive)
sum += primes[j];
if (sum > LIMIT)
break;
else if (j - i > maxRun && sum > maxSum && isPrime[sum]) {
maxSum = sum;
maxRun = j - i;
}
}
}
return Long.toString(maxSum);
}
}
No comments :
Post a Comment