Skip to content

Instantly share code, notes, and snippets.

@afzafri
Last active March 23, 2017 15:39
Show Gist options
  • Save afzafri/f25711d9f02259ee5404053cbccba758 to your computer and use it in GitHub Desktop.
Save afzafri/f25711d9f02259ee5404053cbccba758 to your computer and use it in GitHub Desktop.
Finding the Prime Numbers up to any limit using Sieve of Eratosthenes algorithm. Code example in Python
import time
start_time = time.clock()
# using Sieve of Eratosthenes algorithm
limit = 10000000
# set objects is more faster
not_primenums = set()
primes = set()
print "Generate prime numbers under ", limit
for i in range(2,limit+1):
if i not in not_primenums:
primes.add(i)
for j in range(i*i, limit+1, i):
# store multiple of the prime in here (not prime)
not_primenums.add(j)
print "\nExecution time for generating primes: ", time.clock() - start_time, " seconds"
print "\nNumber of prime numbers generated: ", len(primes)
'''
References
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://www.onlinemathlearning.com/sieve-eratosthenes.html
https://www.quora.com/What-is-Sieve-of-Eratosthenes-can-someone-explain
https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Python
https://iamrafiul.wordpress.com/2013/04/28/sieve-of-eratosthenes-in-python/
'''
# limit, to find prime numbers under 100
lim = 100
# create array/list from 1 to the limit
nums = range(1,lim+1)
primenum = [] # we will store the primes in this list
# iterate through the numbers
# check for the multiples for each prime
# if true, break the loop, and store the prime number into the list
for i in range(1,len(nums)):
for j in range(2,nums[i]):
if nums[i]%j == 0:
break
else:
primenum.append(nums[i])
print primenum
'''
References
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://www.onlinemathlearning.com/sieve-eratosthenes.html
https://www.quora.com/What-is-Sieve-of-Eratosthenes-can-someone-explain
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment