在 Python 中检查数字是否是列表中的质数

Dan*_*ny 0 python python-3.x

我写了下面的代码,它应该检查列表中的数字是否是质数,但是有一个我无法解决的问题,因为我正在尝试实现对平方根的检查优化num,我有一个类型错误。

def is_prime(x):
    if x <= 1:
        return False
    if x == 2:
        return True
    for n in range(3, x**(0.5)+1, 2):   # this skips even numbers and only checks up to sqrt(x)
        if x % n == 0:
            return False
    return True


my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))

print(result)
Run Code Online (Sandbox Code Playgroud)
  File "PrimeCheck.py", line 39, in <module>
    result = list(map(is_prime,my_list))
  File "PrimeCheck.py", line 32, in is_prime
    for n in range(3, x**(0.5)+1, 2):   # this skips even numbers and only checks up to sqrt(x)
TypeError: 'float' object cannot be interpreted as an intege
Run Code Online (Sandbox Code Playgroud)

asi*_*ero 5

x**(0.5)+1不是整数,因此range无法生成列表。

尝试四舍五入:

from math import ceil
def is_prime(x):

    if x <= 1:
        return False
    if x == 2:
        return True
    for n in range(3, ceil(x**(0.5)), 2):   # this skips even numbers and only checks up to sqrt(x)
        if x % n == 0:
            return False
    return True


my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))

print(result)
Run Code Online (Sandbox Code Playgroud)