Hello I have created this program to check if a number is a prime number. It works but for some reason says that 999 is a prime number. Where is my mistake. It would be great if someone explained. Thank You!
Here is my program:
number = raw_input('Enter a Number: ')
nnumber = int(number)
prime_range = range(2, nnumber)
for x in prime_range:
if nnumber % x == 0:
print 'Not a Prime Number!'
break
else:
print 'Prime Number!'
break
Trace it. x
starts with 2
, then tests 999 % 2
; it is 1
, so else
is executed, "Prime number!" is printed, and loop is broken out of. Program ends.
Instead, you need to print "Prime number!" only when you tested all possibilities for x
. The easiest way to do that is to unindent else:
(and delete break
there):
for x in prime_range:
if nnumber % x == 0:
print 'Not a Prime Number!'
break
else:
print 'Prime Number!'
Python executes else
of a for
when for
completes withoout being broken: exactly what you want.
If a number is prime, that means no number evenly divides it besides 1 and itself. That mean you need to check every number below it before being able to say the number is prime.
In your code, you are exiting the loop on the first iteration -- regardless of how large the number is.
The judgment has a problem, can only be 1 or the prime number is divisible by itself. You judge is only 2 out of the whole is not a prime number, you should use a double loop to do the conditions of judgment
you are checking for the 1st iteration only. Irrespective of whether it is prime or not it exits from the loop since one of the section i.e either 'if' or 'else' will execute causing the loop to break. The logic would be to check for the entire range of numbers from 2 to (number/2) and if it divides the number at some point it will not be a prime number. If the loop exits after iterating over the entire loop then it is a prime number. Hope you will be able to do it now. Thanks!.
Your existing code only every tests if the number that you entered is divisible by 2 and then breaks out of the loop, whichever way. You have to check all values lower and only exit if it does find that it's NOT a prime:
number = raw_input('Enter a Number: ')
nnumber = int(number)
prime_range = range(2, nnumber)
prime = True
for x in prime_range:
if nnumber % x == 0:
prime = False
break
if prime:
print 'Prime Number!'
else:
print 'Not a Prime Number!'