## Prime Generator

Inspired by the last post, just thought this was too cool not to share. The function generates primes!

def prime_gen(): '''Generate primes.''' offset = 2 index = offset sieve = range(offset, offset ** 2) found = [] while 1: start = index ** 2 end = (index + 1) ** 2 sieve.extend(range(start, end)) num = sieve[index - offset] if num: found.append(num) sieve = sieve[index - offset:] offset = num yield num i = 0 while i < len(found): curr = found[i] j = start / curr * curr while j < len(sieve) + offset: sieve[j - offset] = 0 j += curr i += 1 index += 1</pre>

(Not related to this post) You might like to use the sourcecode shortcode to format sourcecodes. Here’s the link from wp.com support: http://en.support.wordpress.com/code/posting-source-code/

phoxis2011/07/14 at 00:44

Ah, that’s very useful. Much appreciated.

Ceasar Bautista2011/07/15 at 14:58