Reputation: 19
I'm fairly new to coding but I'm having an issue with my code. The code seems to work with every test number and I can tell why.
num1 = int(input('Please enter a positive integer: '))
def is_prime(x):
if x <= 1 :
return False
elif x == 2:
return True
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
print(is_prime(num1))
4
is returning a True
value when it should be False
.
Upvotes: 1
Views: 92
Reputation: 3170
This is your culprit:
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
Your step term in range
is 2 starting at 3, so 4 doesn't get tested. Because it isn't tested, your function just returns True
.
You can fix this naively by adding another elif
checking input mod 2 before your range.
def is_prime(x):
if x <= 1 :
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
for n in range(3,x-1,2):
if x % n == 0:
return False
return True
Upvotes: 2