Last active
May 17, 2024 20:27
-
-
Save chinchalinchin/974a1a78e463029f3246997564201ecc to your computer and use it in GitHub Desktop.
Sieve of Erastothenes Algorithm for Finding Prime Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _squares(n): | |
""" | |
Arguments: | |
n (int): arbitray integer | |
Returns: | |
a list of squares up to the value of ``n``. | |
""" | |
return [ | |
i*i | |
for i in range(1, n+1) | |
if i*i < n | |
] | |
def primes(n): | |
""" | |
Arguments: | |
n (int): arbitrary integer | |
Returns: | |
A list of primes up to the values of ``n`` | |
""" | |
sqs = _squares(n) | |
sieve = { | |
x: True | |
for x in range(2,n+1) | |
} | |
# NOTE: len(sqs) + 2 gives the next closest root of a perfect square | |
for i in range(2, len(sqs) + 2): | |
if sieve[i]: | |
for j in range(1+1, n // i + 1): | |
sieve[i*j] = False | |
return [ k for k,v in sieve.items() if v ] | |
if __name__== "__main__": | |
print(primes(300)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment