Skip to content

Instantly share code, notes, and snippets.

@uchida
Created February 1, 2012 13:45
Show Gist options
  • Select an option

  • Save uchida/1717002 to your computer and use it in GitHub Desktop.

Select an option

Save uchida/1717002 to your computer and use it in GitHub Desktop.
prime numbers generator
#!/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