Created
August 4, 2013 14:15
-
-
Save samueljackson92/6150461 to your computer and use it in GitHub Desktop.
Sieve Of Eratosthenes
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
#!/usr/bin/env python | |
################################################ | |
# Sieve Of Eratosthenes | |
# Implementation the sieve of eratosthenes for | |
# finding all prime numbers up to a given limit | |
# Author: Samuel Jackson ([email protected]) | |
# Date: 4/8/13 | |
################################################ | |
import math | |
def sofe(n): | |
#list of flags from 2 to n indidcating if a number is prime | |
lstFlags = [True]*n | |
#for each number between 2 and the largest possible divisor of the limit | |
for i in range(2, 1+int(math.sqrt(n))): | |
#check if the current number is prime | |
if(lstFlags[i] is True): | |
#if so, remove any multiples of i from the pool | |
for j in range(i**2, n, i): | |
lstFlags[j] = False | |
#filter the list of flags to return only the primes. | |
return [i for i, x in enumerate(lstFlags) if x is True and i > 1] | |
if __name__ == "__main__": | |
number = raw_input("Input a number: ") | |
try: | |
number = int(number) | |
except exceptions.ValueError: | |
print "That wasn't a number!" | |
print sofe(number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment