Reputation: 11
I wrote the following code to check for whether a number is prime. While there are more efficient ways to do this, I did notice that while this works for the largest of the primes, it breaks for every product of primes. So, while it correctly identifies 13 and 17 as primes, it also identifies 91 (13 × 7) as prime. Any ideas why?
def checkifprime(numtocheck):
for x in range(2,numtocheck):
if(numtocheck % x == 0):
return False
return True
answer = checkifprime(91)
print (answer)
Upvotes: 1
Views: 415
Reputation: 311393
The return True
statement isn't indented properly - you've placed it inside the for
loop. So, the loop starts with 2
, and if the number is odd it doesn't enter the if
and then returns True
. You should place this statement after the for
loop. Only once the loop is exhausted, if you didn't find any appropriate divisor, can you return that this number is a prime:
def checkifprime(numtocheck):
for x in range(2,numtocheck):
if(numtocheck % x == 0):
return False
return True # Note the indendation
Upvotes: 2
Reputation: 86084
Your program never gets farther than the first iteration. What you effectively have is an even-or-oddness checker. The program always returns in the first iteration of the loop. You are returning True
too early.
Upvotes: 2
Reputation: 224922
return True
is indented too far; it’s inside the loop and causes the function to exit on the first iteration, so your function really only checks whether a number is odd.
def checkifprime(numtocheck):
for x in range(2, numtocheck):
if numtocheck % x == 0:
return False
return True
Upvotes: 5