Sep-30-2019, 01:08 PM
The problem with 2 is that your for loop on line 11 is then
The problem with 9 (and every other odd composite number) is that you break out of the for loop as soon as you get a number that is not a divisor. So the first thing you check is 2, which doesn't divide 9 evenly, so you said 9 is prime without going on to check 3, 4, 5, and so on.
For loops have a handy else construction. If a for loop has an else, the else triggers if the loop finished without a break statement. So if you just dedent the else on line 16, so that it is associated with the for loop on line 11 instead of the if statement on line 12, it should work:
for div in range(2, 2):
. That range is empty. So the loop never executes and 2 is never checked.The problem with 9 (and every other odd composite number) is that you break out of the for loop as soon as you get a number that is not a divisor. So the first thing you check is 2, which doesn't divide 9 evenly, so you said 9 is prime without going on to check 3, 4, 5, and so on.
For loops have a handy else construction. If a for loop has an else, the else triggers if the loop finished without a break statement. So if you just dedent the else on line 16, so that it is associated with the for loop on line 11 instead of the if statement on line 12, it should work:
for div in range(2,num): # testing whether a prime or not if ((num % div) == 0): print(num,"ei ole alkuluku, koska",div,"*",num//div,"=",num) # number is not a prime because ... break else: print(num,"on alkuluku.") # number is prime number breakMaybe that is what you meant to do? If you have not covered else for loops, and cannot use it in this homework, I would recommend setting up a flag variable to indicate a number is not prime:
is_prime = True for div in range(2,num): # testing whether a prime or not if ((num % div) == 0): print(num,"ei ole alkuluku, koska",div,"*",num//div,"=",num) # number is not a prime because ... is_prime = False break if is_prime: print(num,"on alkuluku.") # number is prime number breakThere are some inefficiencies here, but that's not a big deal for a homework assignment (you don't need to check every number less than n, just every prime less than or equal to sqrt(n)). Note that the elif on line 9 can just be an else. Every number is either not 0 or not 1, since no number can be both 0 and 1. So that clause is always True, which is what you want any way.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures