- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 64 lines of C++ from the credited upstream file largest-prime-from-consecutive-prime-sum.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 56const auto& is_prime = [](int n) {7 if (n <= 1 || (n != 2 && n % 2 == 0)) {8 return false;9 }10 for (int i = 3; i <= n; i += 2) {11 if (i * i > n) {12 break;13 }14 if (n % i == 0) {15 return false;16 }17 }18 return true;19};20 21const auto& linear_sieve_of_eratosthenes = [](int n) { 22 vector<int> spf(n + 1, -1);23 vector<int> primes;24 for (int i = 2; i <= n; ++i) {25 if (spf[i] == -1) {26 spf[i] = i;27 primes.emplace_back(i);28 }29 for (const auto& p : primes) {30 if (i * p > n || p > spf[i]) {31 break;32 }33 spf[i * p] = p;34 }35 }36 return pair(primes, spf);37};38 39const auto& precompute = [](int n, int sqrt_n) {40 const auto& [primes, spf] = linear_sieve_of_eratosthenes(sqrt_n);41 vector<int> result = {0};42 int total = 0;43 for (const auto& p : primes) {44 total += p;45 if (total > n) {46 break;47 }48 if ((total < size(spf) && spf[total] == total) || is_prime(total)) {49 result.emplace_back(total);50 }51 }52 return result;53};54 55const int MAX_NUM = 5e5;56const int SQRT_MAX_NUM = 2729; 57const auto& PRIMES = precompute(MAX_NUM, SQRT_MAX_NUM);58class Solution {59public:60 int largestPrime(int n) {61 return *prev(upper_bound(cbegin(PRIMES), cend(PRIMES), n));62 }63};64