Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active December 15, 2016 11:53
Show Gist options
  • Select an option

  • Save TimSC/7ad860dab639af5942e47ca7fb5b04f7 to your computer and use it in GitHub Desktop.

Select an option

Save TimSC/7ad860dab639af5942e47ca7fb5b04f7 to your computer and use it in GitHub Desktop.
Sieve Of Eratosthenes in python
import math
class SieveOfEratosthenes(object):
def __init__(self, limit1, limit2 = None):
if limit2 is None:
self.lowerLimit = 2
self.upperLimit = limit1
else:
if limit1 <= 1:
raise RuntimeError("Lower limit must be at least 2")
self.lowerLimit = limit1
self.upperLimit = limit2
self.vals = set(range(self.lowerLimit, self.upperLimit))
iLim = math.ceil(self.upperLimit ** 0.5)
#Remove even numbers
i = 2
m = i+i #First multiple of 2
if self.lowerLimit > m:
m = (self.lowerLimit // i) * i
while m < self.upperLimit:
try:
self.vals.remove(m)
except KeyError:
pass
m += i
#Only process odd numbers from here
i = 3
while i <= iLim:
m = i+i #First multiple of i
if self.lowerLimit > m:
m = (self.lowerLimit // i) * i
while m < self.upperLimit:
try:
self.vals.remove(m)
except KeyError:
pass
m += i
i += 2
if __name__=="__main__":
soe = SieveOfEratosthenes(104730)
print "Found", len(soe.vals), "primes"
#Validate against first 10000 primes https://primes.utm.edu/lists/small/10000.txt
primes = set()
fi = open("10000.txt", "rt")
for i in range(4):
fi.readline()
for li in fi.readlines():
if li.strip() == "end.": break
primes.update([int(val.strip()) for val in li.strip().split()])
#primes = set([p for p in primes if p > ii])
if primes != soe.vals:
print "Mismatch"
print "Missing:", primes.difference(soe.vals)
print "Extra:", soe.vals.difference(primes)
else:
print "All good!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment