Reputation: 179
I have a problem with a this piece of code that I'm writing to check if a number is prime.
import sys
import math
def is_prime(num):
for j in range(2,(int(math.sqrt(num)+1))):
if (num % j) == 0:
return False
else:
return True
for a in range(1,10):
if is_prime(a):
print a
What I get is: 5, 7, 9
I don't understand why is 3 excluded? I went back to the first portion of the code and tried is_prime(3)
, but it returned me neither True nor False. Does this mean that 3 is outside the range of divisors I'm checking? How should I correct the code such that 3 is included in my list of primes?
Edit:
Hello again, thanks for the answers so far, so I've tried to solve the problem of truncation using int(round()). I've also tried putting the else
block outside the loop, but it doesn't seem to work. Can anyone please explain why this is insufficient and suggest how I should correct it so it works? Thanks in advance! :)
import sys
import math
def is_prime(num):
for j in range(2,int(round(math.sqrt(num)+1)):
if (num % j) == 0:
return False
return True
Upvotes: 2
Views: 323
Reputation: 298364
int()
truncates, not rounds, so int(math.sqrt(3) + 1) == 2
. range(2, 2)
is empty, so nothing will be returned.
Another problem is that your else
block is inside of the loop. If you test the first 100 numbers, you will quickly notice that your is_prime
function will return True
for any odd number.
Upvotes: 1
Reputation: 500683
Your function returns True
as soon as it sees that the number is not divisible by any j
. It should only return True
if the number is not divisible by all j
.
As a side-effect of fixing this bug, you'll also fix the bug whereby your function sometimes returns None
(for example, when num
is 3
).
Upvotes: 2
Reputation: 71
The square root of 3 is less than 2, so the loop is never entered and nothing is returned.
Upvotes: 0