质数检测器在某些数字上失败


def is_prime(x):
    list1 = []
    count = 1
    if x < 0:
        return False
    elif x == 1:
        return False
    elif x == 2:
        return True
    for item in range(x):
        list1.append(x - count)
        count += 1 
        if count == x:
            list1.remove(1)
    for item in list1:
        if x / item == 1:
            return False
    else:
        return True

这是失败的一些数字,我不确定为什么。我很确定这主要是我的数学问题,或者是我对质数的理解问题?我正在通过代码学院学习,所以请随意提示我正确的方向,而不是直接给我答案。提前感谢大家!

似乎你正在使用Python 2,而Python 3和Python 2之间的除法操作的差异导致了你的问题。在Python 2中,普通除法得到一个整数,例如5/4=1,而在Python 3中,5/4=1.25。所以,在python中,2,5可以被当作函数中的非素数。

除了除法,你可以尝试其他数学运算,如模块%来做判断。

查看两个数相除时返回余数的模运算符

>>> 4 % 2
0
>>> 5 % 2
1
import math
def is_prime(x):
    count = 0
    if x < 0:
        return False
    elif x == 1:
        return False
    elif x == 2:
        return True
    for n in range(1,int(math.ceil(math.sqrt(x)))+1): #only looks up to sqrt(x)
        if not x % n: #if n is divisor of x then it is factor
            count += 1
        if count > 1: #if we have 2 or more factors then it isn't a prime 
            return False
    return True
一些测试:

print(all(is_prime(p) for p in [2, 3, 5, 7, 11, 23, 29, 41, 43, 47, 61, 67, 83, 89, 101, 113, 131]))
print(any(is_prime(np) for np in [1,4,6,8,9,10,12,14,15,16]))
>>> 
True
False

试试这个,我只测试了几个数字:

def is_prime(n):
    i = 2
    sq_root_n = n**0.5
    if n <= 0:
        return False
    while i < sq_root_n:
        if n % i == 0:
            return False
        i += 1
    return True
    def is_prime(x):
    maxdiv = x - 1
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x >= 2:
        for n in range(2,maxdiv):
            if x % n == 0:
                print '%d is not prime. I divided it by %d' % (x, n)
                return False
        else:
            return True

最新更新