【问题标题】:Why is my prime number function not working?为什么我的素数函数不起作用?
【发布时间】:2016-08-02 09:22:07
【问题描述】:

我是编程新手,在尝试编写程序以找出素数时遇到问题。这是我的代码:

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for n in range (2,x-1):
            if x % n == 0:
                return False
            else:
                return True

我收到一条错误消息,指出“您的函数在 is_prime(3) 上失败。它在应该返回 True 时返回 None。”

有人能解释一下这段代码的缺陷吗?

谢谢!

【问题讨论】:

  • 您的循环在第一次迭代中总是返回TrueFalse(如果没有迭代则什么都没有)。如果 整个循环 完成但没有找到任何因素,您应该只返回 True

标签: python if-statement for-loop primes prime-factoring


【解决方案1】:

range() 有一个exclusive upper bound,因此它试图获取 2 到 2 (3 - 1) 之间的范围,即没有元素。由于您不能对任何内容进行迭代,因此 for 循环永远不会运行,因此返回 None(如果未指定,这是函数的默认返回类型)。

解决您当前问题的方法是使用range(2, x) 而不是range(2, x - 1)。您会发现在 x > 3 处会出现问题,因为正如@khelwood 所说,您在检查第一个值后立即返回TrueFalse。相反,仅在检查范围内的所有值后返回True

【讨论】:

  • 可能值得明确指出解决方案是使用range(x)
【解决方案2】:
def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for n in range (2,x): # range function will iterate till x-1
            if x % n == 0:
                return False
        # return true only at the end after making sure it is not divisible by any number in the middle
        return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-21
    • 2021-12-18
    • 2011-06-23
    • 1970-01-01
    • 2017-08-18
    • 2010-10-18
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多