Reputation: 13
Working on a program in python to print out the first 1000 prime numbers (except 2). all i can get for the output is the number 3. don't understand where or when my loop is ending. very new at programming. can anybody help?
primeCounter = 1
candidate = 3
while primeCounter < 1000:
isPrime = True
counter = 2
while counter < candidate:
if candidate%counter == 0:
isPrime = False
else:
counter = counter + 1
if isPrime == True:
print candidate
primeCounter = primeCounter + 1
candidate = candidate + 1
Upvotes: 1
Views: 2648
Reputation: 1283
Your problem in block
while counter < candidate:
if candidate%counter == 0:
isPrime = False
if not candidate % counter, you get infinity loop.
Upvotes: 0
Reputation: 182875
Once you set isPrime
to False
, you never increment counter
again, so you never get out of the inner while
loop.
Upvotes: 2
Reputation: 18229
primeCounter = 1
candidate = 3
while primeCounter < 1000:
isPrime = True
counter = 2
while counter < candidate:
if candidate%counter == 0:
isPrime = False
break # <<<<<<<<<<<<<<<<< break here, or the loop will go infinite
else:
counter = counter + 1
if isPrime == True:
print candidate
primeCounter = primeCounter + 1
candidate = candidate + 1
Upvotes: 3