簡體   English   中英

檢查列表中的數字是否為質數

[英]Checking if a number from a list is a prime number

我寫了下面的代碼,它應該檢查列表中的數字是否是質數,但是有一個問題我無法解決,因為我正在嘗試實現檢查到平方根的優化的數字,我有一個TypeError

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)

  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 integer

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)

表達方式:

range(3, x**(0.5)+1, 2):

提升為浮點類型,因為

x**(0.5)

對於您想要的行為,您需要再次將其設為 int,請嘗試:

range(3, int(round(x**(0.5)+1)), 2):

在哪里

int(x)

告訴 python 你想將 x 解釋為整數類型

round(x)

返回最接近 x 的整數。

請注意,舍入可能不是您所期望的:

https://docs.python.org/2/library/functions.html#round

在此處輸入圖像描述 檢查列表中的數字,如果該數字是素數並將素數附加到列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM