简体   繁体   中英

Prime number checking function not working on a test case

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM