Largest Prime from Consecutive Prime Sum

You are given an integer n.

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
Inputn = 20
Output17
The prime numbers less than or equal to n = 20 which are consecutive prime sums are 2, 5, and 17, so the largest is 17.
Example 2
Inputn = 2
Output2
The only consecutive prime sum less than or equal to 2 is 2 itself.

Constraints

  • 1 <= n <= 5 * 10^5

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate