Python, prime number checker [duplicate]

烈酒焚心 提交于 2019-12-04 06:41:05

问题


Hi i'm making a function that checks if a number is a prime or not but its telling me that 9 is a prime.

def eprimo(num):
    if num < 2:
        return False
    if num == 2:
        return True
    else:
        for div in range(2,num):
            if num % div == 0:
                return False
            else:
                return True

回答1:


You're going to return from the first iteration of that for loop whether you're done checking or not. You shouldn't return from inside the loop unless the number is definitely not prime. Remove the else and only return True if the loop finishes.

def eprimo(num):
    if num < 2:
        return False
    if num == 2:
        return True
    else:
        for div in range(2,num):
            if num % div == 0:
                return False
        return True

Optimization side note: You really don't need to check all the divisor candidates up to num. You only need to check up to the square root of num.




回答2:


Your for loop exits right after the first iteration when it checks whether your number is divisible by 2. If your number is even, it will return False; otherwise, it will return True.

The solution is not to return True immediately; wait for the end of all the iterations in the loop instead:

for div in range(2, num):
    if num % div == 0:
        return False
return True

Alternatively, use the all() construct:

return all(num % div != 0 for div in range(2, num))



回答3:


Instead of testing all divisors in range(2,num), you could extract the test for even numbers and then loop only on the odd numbers. Additionally, as Bill the Lizard suggests, you could stop at the square root of num. This will be twice as fast:

def eprimo(num):
    if num < 2:
        return False
    if num % 2 == 0:
        return num == 2
    div = 3
    while div * div <= num:
        if num % div == 0:
            return False
        div += 2
    return True


来源:https://stackoverflow.com/questions/19385136/python-prime-number-checker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!