Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to find all primes less than some upperbound efficiently?

"""
Implementation of the "Sieve of Eratosthenes" 
algorithm.
It aims at finding all primes that are less 
than or equal to a certain upperbound, 
denoted by n. 
Time complexity: O(n log log n) 
Space complexity: O(n)
"""
import math

def findPrimes(n):
    # Only 1 prime <= 2
    if n <= 2:
        return [2]
    """
    Initialize numbers[0] and numbers[1] as False
    because 0 and 1 are not prime.
    Set numbers[2] through numbers[n-1] to True
    When we find a divisor for one of them, set
    it to False
    """
    numbers = [False, False] + [True] * (n - 1)
    sqrtN = int(math.sqrt(n))
    for p in range(2, sqrtN + 1):
        if numbers[p]:
            # Set all multiples of p to false
            # because they are not prime.
            for multiple in range(p * p, n+1, p):
                numbers[multiple] = False
    # put all primes in a list
    result = []
    for p in range(n+1):
        if numbers[p]:
            result.append(p)
    return result

print(findPrimes(13))  # [2, 3, 5, 7, 11, 13]
print(findPrimes(19))  # [2, 3, 5, 7, 11, 13, 17, 19]
Comment

PREVIOUS NEXT
Code Example
Python :: json post python with headers 
Python :: pip install dal 
Python :: python check if variable is string 
Python :: list to tensor 
Python :: how to set the size of a gui in python 
Python :: ros python subscriber 
Python :: shuffle rows dataframe 
Python :: pandas select row by index 
Python :: how to create an empty 2d list in python 
Python :: how to extract zip file in jupyter notebook 
Python :: plt.imshow not showing 
Python :: how to make any player hit a ball using python turtle 
Python :: do you have to qualift for mosp twice? 
Python :: robot append to list with for loop 
Python :: add field placeholder layout crispy modelform 
Python :: epoch to datetime utc python 
Python :: python for i in directory 
Python :: pandas query variable count 
Python :: python inheritance remove an attribute 
Python :: how to clear screen python 
Python :: plotly scatter markers size 
Python :: adaptive thresholding cv2 python 
Python :: how to map array of string to int in python 
Python :: save plot as image python matplotlib 
Python :: python rock paper scissor 
Python :: count plot 
Python :: how to print an input backwards in python 
Python :: python for doing os command execution 
Python :: create jwt token python 
Python :: return column of matrix numpy 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =