[Tutor] Spurious primes

Sarney sarney@bigpond.com
Wed, 30 Jan 2002 21:41:54 +1100


Dear list members,

I'm attempting to 'think like a computer scientist'.  To this end, I set
myself a trivial exercise of generating a list of primes.  I thought I had
succeeded with the function below (after much gnashing of teeth & re-reading
tutorials).  My pride was dashed when my I asked for 7 primes and got
(2,3,5,7,11,13,16).  After some more testing, I realised it was spitting out
these spurious primes after testing a number with more than one factor in
the list 'a' (e.g 15 & 21).

Where have I gone wrong?

Regards, Robert
________________________

a = [2]

def test(x,a):
   for i in a:
      if x%i == 0:
         x = x + 1
         test(x,a)

      else:
         return x

num = int(raw_input("how many primes do you want? "))

while len(a) <= num - 1:
   a.append(test(a[-1]+1,a))


print a