Problem solution · Python

Largest Prime from Consecutive Prime Sum

Largest Prime from Consecutive Prime Sum: a Python solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Binary search
Source
Kamyu LeetCode Solutions
Length
57 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Largest Prime from Consecutive Prime Sum, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeLargest Prime from Consecutive Prime Sum · PythonPython
Use this to learn the idea, then write your own version.
# Time:  precompute: O(sqrt(r) * sqrt(r)) = O(r)#        runtime:    O(logp), p = len(PRIMES)# Space: O(sqrt(r)) import bisect  # precompute, number theory, binary searchdef is_prime(n):    if (n <= 1) or (n != 2 and n%2 == 0):        return False    for i in xrange(3, n+1, 2):        if i*i > n:            break        if n%i == 0:            return False    return True  def linear_sieve_of_eratosthenes(n):  # Time: O(n), Space: O(n)    primes = []    spf = [-1]*(n+1)  # the smallest prime factor    for i in xrange(2, n+1):        if spf[i] == -1:            spf[i] = i            primes.append(i)        for p in primes:            if i*p > n or p > spf[i]:                break            spf[i*p] = p    return primes, spf  def precompute(n, sqrt_n):    result = [0]    primes, spf = linear_sieve_of_eratosthenes(sqrt_n)    total = 0    for p in primes:        total += p        if total > n:            break        if (total < len(spf) and spf[total] == total) or is_prime(total):            result.append(total)    return result  MAX_NUM = 5*10**5SQRT_MAX_NUM = 2729  # by precomputationPRIMES = precompute(MAX_NUM, SQRT_MAX_NUM)class Solution(object):    def largestPrime(self, n):        """        :type n: int        :rtype: int        """        return PRIMES[bisect.bisect_right(PRIMES, n)-1] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗