Newbie question - calculating prime numbers

Peter Otten __peter__ at
Tue Aug 10 15:18:31 CEST 2010

Matty Sarro wrote:

> Hey Dave,
> Thank you for the heads up. I actually bashed my head against the desk a
> few times and eventually I realized what I was doing wrong. Here's my
> final code (slightly optimized) that's verified and working. Out of
> curiousity, what other optimizations could I throw at it (without diving
> too deep too fast).
> #Assignment 1a
> #Determine the 1000th prime number
> candidate=1
> #Already know that 2 is prime
> primeCount=1
> while (primeCount<=1000):
>         isPrime="true"
>         i=2
>         halfCand=(candidate/2)
>         while (isPrime=="true") and (i<=halfCand):
>                 if ((candidate%i)==0):
>                         isPrime="false"
>                 else:
>                         i+=1
>         if isPrime=="true":
>                 print(candidate, "is a prime.")
>                 primeCount+=1
>         #else:
>                 #print(candidate, " is not a prime.")
>         candidate+=2
> print("The 1000th prime number is ",(candidate-2))


One obvious thing would be to replace the "true" and "false" strings with 
actual boolean values:

isPrime = True
while isPrime and i <= halfCand:


For a different perspective on the problem have a look at


More information about the Python-list mailing list