Ray Holt wrote:
I have an assigment to find the 1000th. prime using python. What's wrong
with the following code:
PrimeCount = 0
PrimeCandidate = 1
while PrimeCount < 2000:
    IsPrime = True
    PrimeCandidate = PrimeCandidate + 2
    for x in range(2, PrimeCandidate):
        if PrimeCandidate % x == 0:
##            print PrimeCandidate, 'equals', x, '*', PrimeCandidate/x
print PrimeCandidate IsPrime = False
              break
        if IsPrime:
            PrimeCount = PrimeCount + 1
            PrimeCandidate = PrimeCandidate + 2
        print PrimeCandidate
Thanks

There are a bunch of things wrong here. Did you write this code, or was it copied from somewhere else? Because it looks like there are several typos, that you could catch by inspection.

First, at what point in the loop do you decide that you have a prime? Why not add a print there, printing the prime, instead of printing a value that's already been incremented beyond it. And put labels on your prints, or you'll never be able to decipher the output. Chnage the limit for PrimeCount to something small while you're debugging, because you can figure out small primes and composites by hand.

Second, you have a loop which divides by x. But you change the PrimeCandidate within the loop, so it's not dividing the same value each time through. Check your indentation.

Third, your limit value is too high. You aren't looking for 2000 primes, but 1000 of them. Further, your count is off by 1, as this loop doesn't identify 2 as a prime.

I'd recommend making this whole thing a function, and have it actually build and return a list of primes. Then the caller can check both the size of the list and do a double check of the primality of each member. And naturally you'll be able to more readily check it yourself, either by eye or by comparing it to one of the standard list of primes you can find on the internet.


The function should take a count, and loop until the len(primelist) matches the count. Then just return the primelist.

DaveA

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to