Largest Prime from Consecutive Prime Sum

You are given an integer n.

Find the largest prime number that is less than or equal to n and can be expressed as the sum of a contiguous prefix of prime numbers. In other words, the sum must strictly be formed by adding consecutive prime numbers starting from the very first prime, 2.

If no such prime number exists within the limit, return 0.

Example 1:

Input: n = 45

Output: 41

Explanation:

The prefix sums of consecutive primes starting from 2 are: 2, 5, 10, 17, 28, and 41. The sums that are prime are 2, 5, 17, and 41. The largest one <=45 is 41.

Example 2:

Input: n = 4

Output: 2

Explanation:

The very first prefix sum is 2. The next is 2 + 3 = 5, which exceeds 4. Thus, the only valid prime sum within the limit is 2.

Now Your Turn!

Pick the correct output for the given input

Input: n = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 5*105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int largestPrime(int n) {
}
};
Test Case

Input:

N