Last active
August 29, 2015 14:07
-
-
Save alexandre/e4eab22155807b0ff587 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/python3 | |
| from math import sqrt | |
| def sieve(limit, limit_list=[]): | |
| ''' | |
| Sieve of Eratosthenes - The sieve of Eratosthenes is one of the most | |
| efficient ways to find all of the smaller primes (below 10 million or so). | |
| >>> sieve(30) | |
| [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29] | |
| ''' | |
| max_num = int(sqrt(limit)) | |
| limit_list = [n for n in range(2, limit)] | |
| first_el = limit_list[0] | |
| limit_list = [first_el] + [n for n in limit_list if n % first_el > 0] | |
| return (first_el != max_num and limit_list) or sieve(limit, limit_list) | |
| print(sieve(int(input('the limit: ')))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment