简体   繁体   English

在Python中查找素数

[英]Finding prime numbers in Python

I need to write a function, is_prime() , which takes in an integer n > 1 and returns TRUE if the number is a prime number and False otherwise. 我需要编写一个函数is_prime() ,该函数接受整数n> 1,如果数字是素数则返回TRUE否则返回False But when I input 2, it always returns False . 但是当我输入2时,它总是返回False Is there anyway to correct this? 反正有没有纠正这个问题?

def is_prime(x):
    if(x > 1):
        for i in range(2,x+1):
            if( x % i == 0):
                return False
            else:
                return True
    else:
        return False

Instead of doing this, you can also use SymPy module 除了这样做,您还可以使用SymPy模块

import sympy

sympy.isprime(5)

Result : 结果:

True

Two issues: 两个问题:
First issue is that range includes the number itself, which means that it will always return true (for numbers > 1) because prime numbers can divide themselves... 第一个问题是范围包括数字本身,这意味着它将始终返回true(对于数字> 1),因为质数可以除以自身。

Fix: change range(2,x+1) to: range(2, x) 修复:将range(2,x+1)更改为: range(2, x)

Second issue, the first else should be aligned with the for (we return true only after trying all the numbers and making sure that none of them divides x ) 第二个问题,第一else应与对齐for (我们只是想所有的号码,并确保他们没有划分后返回true x

Fixed code: 固定代码:

def is_prime(x):
    if x > 1:
        for i in range(2,x):
            if x % i == 0:
                return False
        else:
            return True
    else:
        return False

Although @alfasin's solution is correct (+1), I find the use of else makes it slightly more challenging to understand. 尽管@alfasin的解决方案是正确的(+1),但我发现使用else会使理解起来有些困难。

The else on the for loop in particular required me to reread the Python documentation as most sources say that the else means no break but it really means completed normally , which is true in the case of a loop that didn't run at all! 尤其是在for循环上的else需要我重新阅读Python文档,因为大多数资料都说else 没有中断,但实际上意味着正常完成了 ,这对于完全没有运行的循环来说是正确的!

Here's my rework removing the else statements which aren't strictly needed: 这是我的重做,删除了并非严格需要的else语句:

def is_prime(x):
    if x > 1:
        for i in range(2, x):
            if x % i == 0:
                return False

        return True

    return False

As others will point out, this is probably as inefficient a prime test as you can write. 正如其他人将指出的那样,这可能是您编写的主要测试的效率低下。 But it works. 但这有效。

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

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