Python Forum

Full Version: Prime numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
Can someone please help me understand what is wrong with this code?
print("The prime numbers are:")
num = 0
div = 1
check = 0
while True:
    pri = (num/div)
    try:
        int(pri)
        check += 1
        if div > num and check == 2:
            print(num)
            num += 1
            div = 1
            check = 0
        else:
            div += 1
    except ValueError:
        if div > num and check == 2:
            print(num)
            num += 1
            div = 1
            check = 0
        else:
            div += 1
I'm trying to make a program that showes all the prime numbers.
Your code is going into an infinite loop because of the way num, check and div are increasing. Once num is 2, by the time div gets to 3 (and div > num) check is also 3, and therefore will never equal 2. So the expression on line 10 is never again True, and the numbers just keep increasing.

I think the real problem is that you are expecting int(pri) to raise a value error if pri is not an integer. That's not what int() does. It converts a value to an integer, and only raises the error if it can't be converted. But pri is a float, and floats can always be converted to ints.

The way to check if div evenly divides num is [inline]num % div == 0[/inline. The modulus (%) operator gives you the remainder after dividing num by div. So if it's zero, div evenly divides num.

Note that you want to start at 2, because 0 and 1 are not prime.

Also, you don't have to check every number up to num. You just have to check every number up to the square root of num. In fact, you only need to check every prime number up to the square root of num.