#3770
Largest Prime from Consecutive Prime Sum
MediumArrayMathNumber TheorySieve of EratosthenesCumulative Sums
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log log n)Space O(n)
Use the Sieve of Eratosthenes to generate primes efficiently and compute their cumulative sums to find the largest prime sum.
⚙️
Algorithm
3 steps- 1Step 1: Use the Sieve of Eratosthenes to generate all primes up to n.
- 2Step 2: Compute cumulative sums of these primes.
- 3Step 3: Check which of these sums are prime and less than or equal to n, returning the largest.
solution.py22 lines
1def sieve(n):
2 is_prime = [True] * (n + 1)
3 p = 2
4 while (p * p <= n):
5 if is_prime[p]:
6 for i in range(p * p, n + 1, p):
7 is_prime[i] = False
8 p += 1
9 return [p for p in range(2, n + 1) if is_prime[p]]
10
11def largest_prime_sum(n):
12 primes = sieve(n)
13 prime_set = set(primes)
14 cum_sum = 0
15 max_prime = 0
16 for prime in primes:
17 cum_sum += prime
18 if cum_sum > n:
19 break
20 if cum_sum in prime_set:
21 max_prime = max(max_prime, cum_sum)
22 return max_primeℹ
Complexity note: Sieve of Eratosthenes runs in O(n log log n) and we store primes in a set for O(1) lookups.
- 1Consecutive sums of primes can yield primes themselves.
- 2Using sets allows for quick prime existence checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.