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 .
1 | public interface EulerSolution{ |
2 |
3 | public String run(); |
4 |
5 | } |
01 | /* |
02 | * Solution to Project Euler problem 50 |
03 | * By Nayuki Minase |
04 | * |
07 | */ |
08 |
09 |
10 | public final class p050 implements EulerSolution { |
11 | |
12 | public static void main(String[] args) { |
13 | System.out.println( new p050().run()); |
14 | } |
15 | |
16 | |
17 | private static final int LIMIT = Library.pow( 10 , 6 ); |
18 | |
19 | |
20 | public String run() { |
21 | boolean [] isPrime = Library.listPrimality(LIMIT); |
22 | int [] primes = Library.listPrimes(LIMIT); |
23 | |
24 | long maxSum = 0 ; |
25 | int maxRun = - 1 ; |
26 | for ( int i = 0 ; i < primes.length; i++) { // For each index of a starting prime number |
27 | int sum = 0 ; |
28 | for ( int j = i; j < primes.length; j++) { // For each end index (inclusive) |
29 | sum += primes[j]; |
30 | if (sum > LIMIT) |
31 | break ; |
32 | else if (j - i > maxRun && sum > maxSum && isPrime[sum]) { |
33 | maxSum = sum; |
34 | maxRun = j - i; |
35 | } |
36 | } |
37 | } |
38 | return Long.toString(maxSum); |
39 | } |
40 | |
41 | } |
No comments :
Post a Comment