Created
February 1, 2012 13:45
-
-
Save uchida/1717002 to your computer and use it in GitHub Desktop.
prime numbers generator
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 | |
| # -*- coding: utf-8 -*- | |
| from itertools import count, takewhile, islice | |
| def primes(): | |
| yield 2 | |
| yield 3 | |
| primes = [2, 3] | |
| for i in count(start=5, step=6): | |
| for n in (i, i + 2): | |
| limit = n**0.5 + 1 | |
| trial = takewhile(lambda x: x < limit, primes) | |
| if all(n % prime != 0 for prime in trial): | |
| yield n | |
| primes.append(n) | |
| # prime numbers less than 30 | |
| print list(takewhile(lambda x: x<30, primes())) | |
| # 10 prime numbers | |
| print list(islice(primes(), 10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment