[LeetCode] Largest Prime from Consecutive Prime Sum

3770. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Solution {
public:
int largestPrime(int n) {
if(n == 1) return 0;
int sq = sqrt(n) + 1;
vector<int> sieve(n + 1);
for(int i = 2; i <= sq; i++) {
if(sieve[i]) continue;
for(int j = i * i; j <= n; j += i) sieve[j] = 1;
}
int res = 0;
for(int i = 2, sum = 0; sum <= n and i <= n; i++) {
if(sieve[i]) continue;
sum += i;
if(sum <= n and !sieve[sum]) res = sum;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/largest-prime-from-consecutive-prime-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.