0

I'm new to Python, I've only done programming in Java before recently. I am writing a basic program in Python to print out the 1000th prime number and while I did get it to work, for some reason it's also printing out the next 7 numbers unless I use an unnecessary break:

import math

n=2 
location =0

while location < 999 :      
   if location == 998 :
      print n
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

prints

7919
7920
7921
7922
7923
7924
7925
7926

but

while location < 999 :
   if location == 998 :
       print n
        break
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

prints

7919

Can anyone tell me why this is happening? Also when I was trying to fix this, I found that the shell would only print this once, then if I copied the code, whether I altered it or not, it wouldn't print anything. I would need to restart the shell each time I wanted to alter the code.

2
  • Can you try formatting this a little more nicely? Stack overflow will let you format code by highlighting it and pressing Ctrl+K Commented May 30, 2013 at 21:12
  • I've made an attempt at fixing your post, please do verify the meaning is correct. Commented May 30, 2013 at 21:13

2 Answers 2

2

In the first case, you are printing until you have found the next prime. It is continuing in the while loop. And since location == 998 is true, it prints the numbers. Then when it finds the next prime location < 999 resolves to false and the while loop is completed.

You need the break so that the code leaves the while loop when you found the prime.

If you don't want to break move the print out of the loop and reduce the while condition by 1.

while location < 998 :
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

print n
Sign up to request clarification or add additional context in comments.

Comments

1

That break is totally needed. Your code is printing out everything between the 1000th and 1001th prime in the first example. Print doesn't exit, so you're telling your code to print every number it tests while location is 998, but it doesn't actually stop running until location reaches 999.

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.