Generate all prime numbers up to n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #!/usr/bin/env python
def prime(n):
"""
Generate all prime numbers less than n.
"""
yield 2
primes = []
for m in range(3,n,2):
if all(m%p for p in primes):
primes.append(m)
yield m
def main():
print list(prime(1000))
#or a slower one-liner
print [n for n in range(3,1000,2) if all(n%p for p in range(3,n,2))]
if __name__=="__main__":
main()
|
These are not sieves
sieve: (verb) to filter a set of elements based on certain criteria
It is NOT the Sieve of Eratosthene, and I apologize for mistagging; but it is indeed a sieve nonetheless.
This is sieves.
def getprimes(limit): toreturn = [] numbers = [] for i in range(limit): numbers.append(True) for i in range(2, limit): if numbers[i] == True: toreturn.append(i) numbers[i] = False for j in range(i, limit, i): numbers[j] = False return toreturn
A python onliner Sieve: