-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathlargest-prime-from-consecutive-prime-sum.cpp
More file actions
63 lines (59 loc) · 1.58 KB
/
largest-prime-from-consecutive-prime-sum.cpp
File metadata and controls
63 lines (59 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Time: precompute: O(sqrt(r) * sqrt(r)) = O(r)
// runtime: O(logp), p = len(PRIMES)
// Space: O(sqrt(r))
// precompute, number theory, binary search
const auto& is_prime = [](int n) {
if (n <= 1 || (n != 2 && n % 2 == 0)) {
return false;
}
for (int i = 3; i <= n; i += 2) {
if (i * i > n) {
break;
}
if (n % i == 0) {
return false;
}
}
return true;
};
const auto& linear_sieve_of_eratosthenes = [](int n) { // Time: O(n), Space: O(n)
vector<int> spf(n + 1, -1);
vector<int> primes;
for (int i = 2; i <= n; ++i) {
if (spf[i] == -1) {
spf[i] = i;
primes.emplace_back(i);
}
for (const auto& p : primes) {
if (i * p > n || p > spf[i]) {
break;
}
spf[i * p] = p;
}
}
return pair(primes, spf);
};
const auto& precompute = [](int n, int sqrt_n) {
const auto& [primes, spf] = linear_sieve_of_eratosthenes(sqrt_n);
vector<int> result = {0};
int total = 0;
for (const auto& p : primes) {
total += p;
if (total > n) {
break;
}
if ((total < size(spf) && spf[total] == total) || is_prime(total)) {
result.emplace_back(total);
}
}
return result;
};
const int MAX_NUM = 5e5;
const int SQRT_MAX_NUM = 2729; // by precomputation
const auto& PRIMES = precompute(MAX_NUM, SQRT_MAX_NUM);
class Solution {
public:
int largestPrime(int n) {
return *prev(upper_bound(cbegin(PRIMES), cend(PRIMES), n));
}
};