Problem #50 Difficulty: 5%

Consecutive Prime Sum

Solution Language: Java

The problem

Find the prime below one million that is the sum of the longest possible run of consecutive primes.

My solution

Every prime below 10⁶ is generated by trial division and copied into a sorted Integer[]. Then, for each starting index i, the code extends a running sum one prime at a time. Each sum is checked for primality with Arrays.binarySearch on that same array, and the run length j − i + 1 is compared with the best so far. As soon as the sum passes one million, the inner loop ends and the next starting prime is tried.

a:  for(int i = 0; i < length; i++) {
      sum = 0;
      for(int j = i; j < length; j++) {
        sum += arr[j];
        if(sum > maxPrime)
          continue a;

        if(Arrays.binarySearch(arr, sum) >= 0) {
          ...

That cutoff keeps the search small. A run starting at 2 can only go about 550 primes before passing a million, and runs that start at large primes end after a term or two. Across all starting points that’s roughly 730,000 running sums, each with an O(log n) lookup.