Largest Prime from Consecutive Prime Sum Problem
#3770
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3770.
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 * 10^5
Solution
Approach: Preprocessing + Binary Search
Sieve all primes up to 5 * 10^5. Add the primes one by one starting from 2, and whenever the running sum is itself a prime, store it in a sorted list s (together with a sentinel 0). The list is tiny, about 40 values.
For each query n, binary search s for the largest value that is at most n.
Complexity: time O(M log log M) preprocessing and O(log k) per query, space O(M), where M is the sieve limit and k is the length of s.
from bisect import bisect_right
mx = 500000
is_prime = [True] * (mx + 1)
is_prime[0] = is_prime[1] = False
primes = []
for i in range(2, mx + 1):
if is_prime[i]:
primes.append(i)
for j in range(i * i, mx + 1, i):
is_prime[j] = False
s = [0]
t = 0
for x in primes:
t += x
if t > mx:
break
if is_prime[t]:
s.append(t)
class Solution:
def largestPrime(self, n: int) -> int:
i = bisect_right(s, n) - 1
return s[i]