Given an array of limits. For every limit, find the prime number which can be written as the sum of the most consecutive primes smaller than or equal to limit.
The maximum possible value of a limit is 10^4.
Example:
Input : arr[] = {10, 30}
Output : 5, 17
Explanation : There are two limit values 10 and 30.
Below limit 10, 5 is sum of two consecutive primes,
2 and 3. 5 is the prime number which is sum of largest
chain of consecutive below limit 10.
Below limit 30, 17 is sum of four consecutive primes.
2 + 3 + 5 + 7 = 17
Below are steps.
- Find all prime numbers below a maximum limit (10^6) using Sieve of Sundaram and store them in primes[].
- Construct a prefix sum array prime_sum[] for all prime numbers in primes[]
prime_sum[i+1] = prime_sum[i] + primes[i].
Difference between two values in prime_sum[i] and prime_sum[j] represents sum of consecutive primes from index i to index j. - Traverse two loops , outer loop from i (0 to limit) and inner loop from j (0 to i)
- For every i, inner loop traverse (0 to i), we check if current sum of consecutive primes (consSum = prime_sum[i] - prime_sum[j]) is prime number or not (we search consSum in prime[] using Binary search).
- If consSum is prime number then we update the result if the current length is more than length of current result.
Below is implementation of above steps.
Output:
5 17 17 41 953