You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python质数判断代码问题排查:数字27返回结果错误求助

质数判断函数问题排查:27返回错误结果

我了解质数判断有大量现成代码,但我的isPrime函数对数字27无法返回正确结果,希望找出问题所在。假设输入为正整数,以下是我的函数代码:

def isPrime(x):
    """Returns whether or not the given number x is prime.

    A prime number is a natural number greater than 1 that cannot be formed
    by multiplying two smaller natural numbers.

    For example:
    - Calling isPrime(11) will return True
    - Calling isPrime(71) will return True
    - Calling isPrime(12) will return False
    - Calling isPrime(76) will return False
    """
    
    # YOUR CODE HERE
    if x ==1:
        return False
    if x ==2:
        return True
    for a in range(2,x):
        if x %a ==0:
            return False
        else:
            return True

测试时发现,调用isPrime(27)返回了True,但27实际是合数(3×9=27),这是明显的错误。

问题根源

你的循环逻辑存在严重错误:在第一次循环判断a=2时,27除以2余1,触发else分支直接返回True,根本没机会检查后续的因数(比如3)。质数判断需要确认所有小于x的正整数都不能整除x,才能判定为质数,不能在第一次不整除时就直接返回结果。

修正后的代码

把return True移到循环结束之后,确保完成所有可能因数的检查:

def isPrime(x):
    """Returns whether or not the given number x is prime.

    A prime number is a natural number greater than 1 that cannot be formed
    by multiplying two smaller natural numbers.

    For example:
    - Calling isPrime(11) will return True
    - Calling isPrime(71) will return True
    - Calling isPrime(12) will return False
    - Calling isPrime(76) will return False
    """
    
    if x == 1:
        return False
    if x == 2:
        return True
    for a in range(2, x):
        if x % a == 0:
            return False
    # 循环结束后确认没有找到因数,才返回True
    return True

额外优化(可选)

实际上,质数判断不需要检查到x-1,只需要检查到x的平方根即可,能大幅提升效率,优化后的代码如下:

import math

def isPrime(x):
    """Returns whether or not the given number x is prime.

    A prime number is a natural number greater than 1 that cannot be formed
    by multiplying two smaller natural numbers.

    For example:
    - Calling isPrime(11) will return True
    - Calling isPrime(71) will return True
    - Calling isPrime(12) will return False
    - Calling isPrime(76) will return False
    """
    
    if x == 1:
        return False
    if x == 2:
        return True
    # 检查到平方根即可,减少循环次数
    for a in range(2, int(math.sqrt(x)) + 1):
        if x % a == 0:
            return False
    return True

内容的提问来源于stack exchange,提问作者Linnifer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:23:16