- 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
- 57 lines of Python from the credited upstream file largest-prime-from-consecutive-prime-sum.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 5import bisect6 7 89def is_prime(n):10 if (n <= 1) or (n != 2 and n%2 == 0):11 return False12 for i in xrange(3, n+1, 2):13 if i*i > n:14 break15 if n%i == 0:16 return False17 return True18 19 20def linear_sieve_of_eratosthenes(n): 21 primes = []22 spf = [-1]*(n+1) 23 for i in xrange(2, n+1):24 if spf[i] == -1:25 spf[i] = i26 primes.append(i)27 for p in primes:28 if i*p > n or p > spf[i]:29 break30 spf[i*p] = p31 return primes, spf32 33 34def precompute(n, sqrt_n):35 result = [0]36 primes, spf = linear_sieve_of_eratosthenes(sqrt_n)37 total = 038 for p in primes:39 total += p40 if total > n:41 break42 if (total < len(spf) and spf[total] == total) or is_prime(total):43 result.append(total)44 return result45 46 47MAX_NUM = 5*10**548SQRT_MAX_NUM = 2729 49PRIMES = precompute(MAX_NUM, SQRT_MAX_NUM)50class Solution(object):51 def largestPrime(self, n):52 """53 :type n: int54 :rtype: int55 """56 return PRIMES[bisect.bisect_right(PRIMES, n)-1]57