Talentd
FleetCode

3770. Largest Prime from Consecutive Prime Sum

Medium39.0% acceptance2 companies

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:

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

Asked at 2 companies

Hints open one at a time

Hint 1
Generate all prime numbers up to n (use sieve or trial division).
Hint 2
Compute consecutive sums starting from 2 until the sum exceeds n.
Hint 3
Find the largest sum that is also a prime.
11:48
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def largestPrime(self, n: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
20
Input
2
Your code is saved on this device.Solution