1

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
1
  • Have you tried debugging it at all? perhaps by having it output the values of the variables that are tested for conditionals and so forth? Commented Jan 3, 2012 at 3:57

3 Answers 3

3
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
Sign up to request clarification or add additional context in comments.

Comments

2

Once you set isPrime to False, you never increment counter again, so you never get out of the inner while loop.

Comments

0

Your problem in block

while counter < candidate:
    if candidate%counter == 0:
        isPrime = False

if not candidate % counter, you get infinity loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.