Skip to content

Instantly share code, notes, and snippets.

@lattice0
Created June 19, 2014 02:40
Show Gist options
  • Save lattice0/758cd907ba37690b8a04 to your computer and use it in GitHub Desktop.
Save lattice0/758cd907ba37690b8a04 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes - Python Implementation
#PRIMES - 08/06/2013 - LAST EDIT: 09/09/2013
#lucaszanella.com - Primes v1.1
#this is a fast implementation, just for fun. Not the best implementation, but...
#methods:
#var = primes.create()
#--var.generate(max) - generate primes up to 'max' (return: list)
#--var.count(start, end) - count number of primes from 'start' to 'end' (return: int)
#modules
import math
#PRIME NUMBERS - 08/06/2013 - LAST EDIT: 09/06/2013 - NEED FIX error for primes less than a small magnitude (ex: 11)
class create:
def __init__(self):
pass
def generate(self, mn):
self.m = mn + 1
self.ceil = math.ceil(math.sqrt(mn))
#definitions
self.still = True
self.llits = True
self.primes = []
self.x = 0
self.c = 1
#run
for a in range(2, self.m):
self.primes.append(a)
while self.still:
self.c+= 1
self.n = self.c
while self.llits:
self.multiple = self.primes[self.x]*self.n
if self.multiple <= mn:
if self.multiple in self.primes:
self.primes.remove(self.multiple)
else:
self.llits = False
self.n+=1
self.llits = True
self.x+=1
#end still
if self.n==self.ceil:
self.still = False
#end still
return(self.primes)
def count(self, sta, end):
self.count_start = self.generate(sta)
self.count_end = self.generate(end)
self.result = len(self.count_end) - len(self.count_start)
return(self.result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment