简体   繁体   English

Python Prime Checker错误25?

[英]Python prime checker faulty with 25?

So I'm relatively new to Python and trying to define a function which will check to see if a number is prime or not. 因此,我是Python的新手,尝试定义一个函数来检查数字是否为质数。 The code is as follows: 代码如下:

def prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for i in range(3, int((x**0.5)+1)):
            if x % i == 0:
                return False
            else:
                return True

This seems to work for most values however it fails on certain values such as 25, can anyone help to explain to me why? 这似乎适用于大多数值,但是对于某些值(例如25)却无效,有人可以向我解释原因吗? Thanks! 谢谢!

return leaves your function once it is reached. 一旦到达, return就会离开您的函数。 Let's look at the case of 25 . 让我们看一下25的情况。

  • Is x<2 no, so continue. 如果x<2否,请继续。
  • Is it x==2 no, so continue. x==2否,所以继续。
  • Is x divisible by i(=3) ? x是否可被i(=3)整除? No, so go to the else clause, return True leave the function. 否,因此转到else子句, return True离开函数。

See the issue? 看到问题了吗?

To put it another way, for sufficiently large x , your function is equivalent to: 换句话说,对于足够大的 x ,您的函数等效于:

def prime_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        if x % 3 == 0:
            return False
        else:
            return True

It's the 这是

else:

clause, the first i it checks will make it return true. 条款,第一i会检查将使其返回true。

Instead, write 相反,写

else:
    for i in range(3, int((x**0.5)+1)):
        if x % i == 0:
            return False
    return True

EDIT: And as @mata points out, you actually need to start at 2, so it should be for i in range(2, int((x**0.5)+1)): 编辑:正如@mata指出的那样,您实际上需要从2开始,所以它应该是for i in range(2, int((x**0.5)+1)):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM