Return the largest prime number less than or equal to n that can be expressed as the sum of one or more consecutive prime numbers starting from 2. If no such number exists, return 0.
Example 1:
Input:n = 20
Output:17
Explanation:
The prime numbers less than or equal to n = 20 which are consecutive prime sums are:
2 = 2
5 = 2 + 3
17 = 2 + 3 + 5 + 7
The largest is 17, so it is the answer.
Example 2:
Input:n = 2
Output:2
Explanation:
The only consecutive prime sum less than or equal to 2 is 2 itself.
Constraints:
1 <= n <= 5 * 105
Solutions
Solution 1: Preprocessing + Binary Search
We can preprocess a list of all prime numbers less than or equal to \(5 \times 10^5\), then calculate the consecutive prime sums starting from 2, and store those sums that are prime numbers in an array \(s\).
For each query, we simply need to use binary search in array \(s\) to find the maximum value less than or equal to \(n\).
In terms of time complexity, preprocessing the primes takes \(O(M \log \log M)\) time, and each query takes \(O(\log k)\) time, where \(M\) is the upper limit of preprocessing, and \(k\) is the length of array \(s\). In this problem, \(k \leq 40\).