On Sun, Jan 18, 2009 at 3:31 PM, Gregor Lingl <span dir="ltr"><<a href="mailto:gregor.lingl@aon.at">gregor.lingl@aon.at</a>></span> wrote:<br><div class="gmail_quote"><div> </div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Michel Paul's code:<div class="Ih2E3d"><br>
<br>
def primes():<br>
sofar = [-1, 2,3] # a running start, -1 proposed by J.H. Conway<br>
yield sofar[0] # get these out of the way<br>
yield sofar[1] # the only even prime<br>
yield sofar[2] # and then 3<br>
candidate = 5 # we'll increment from here on<br>
while True: # go forever<br>
for factor in sofar[1:]: # skip -1 (or don't use it in the first place)<br>
if factor ** 2 > candidate: # did we pass?<br>
yield candidate # woo hoo!<br>
sofar.append(candidate) # keep the gold<br>
break # onward!<br>
if not candidate % factor: # oops, no remainder<br>
break # this is a composite<br>
candidate += 2 # next odd number please<br>
<br></div>
Time: 100000: 1.58 s 500000: 32.25 s<br>
-----</blockquote><div><br>Actually, that's Kirby's code.<br>This is what I sent:<br><br>def primes():<br> p = [-1, 2, 3]<br> for x in p: yield x<br>
def is_prime(n):<br> for factor in p[1:]:<br> if factor**2 > n: return True<br> if n%factor == 0: return False<br> multiple = 6<br> while True:<br> if is_prime(multiple-1): yield multiple-1; p.append(multiple-1)<br>
if is_prime(multiple+1): yield multiple + 1; p.append(multiple+1)<br> multiple += 6<br><font color="#888888"><br></font>Is this what was tested? Or what was listed? Just curious.<br> </div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
I've modified this one slightly, with a surprising effect<br>
(I conjecture mainly due to avoiding copying p repeatedly):<br>
<br>
def primes():<br>
yield(-1)<br>
p = [2, 3]<div class="Ih2E3d"><br>
for x in p: yield x<br>
def is_prime(n):<br></div>
for factor in p:<div class="Ih2E3d"><br>
if factor**2 > n: return True<br>
if n%factor == 0: return False<br>
multiple = 6<br>
while True:<br></div>
for cand in multiple-1, multiple+1:<br>
if is_prime(cand):<br>
yield cand<br>
p.append(cand)<br>
multiple += 6<br>
<br>
Time: 100000: 0.14 s 500000: 1.05 s<br>
-----<br>
<br>
</blockquote></div><br>Yeah, I like the 'for cand in multiple-1, multiple+1'. I actually did do it that way on a previous occasion. So this is very interesting.<br><br>- Michel<br>