Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Prime numbers
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  prime numbers with iterator and generator cametan_001 8 1,771 Dec-17-2022, 02:41 PM
Last Post: cametan_001
  prime numbers astral_travel 28 3,472 Nov-08-2022, 09:23 PM
Last Post: astral_travel
  Return prime numbers from range krzyfigh 2 1,885 Apr-20-2020, 08:08 PM
Last Post: krzyfigh
  first k non-prime numbers arycloud 11 7,130 Jul-09-2019, 02:19 PM
Last Post: abhi19935
  first k non prime numbers print bsrohith 7 7,419 Jun-20-2019, 10:48 AM
Last Post: arycloud
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,662 May-09-2019, 12:19 PM
Last Post: Pleiades
  Finding prime numbers creslin_black 7 4,298 Jul-20-2018, 02:28 PM
Last Post: grjmmr
  Prime Numbers OmarSinno 1 4,351 Sep-23-2017, 05:29 PM
Last Post: ichabod801
  prime numbers generator is generating non prime numbers? ixaM 2 4,418 Dec-18-2016, 01:35 PM
Last Post: ixaM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020