简体   繁体   English

为什么质数检查器说 9 是质数?

[英]Why does prime number checker say 9 is a prime number?

print "Type a number"
num = int(raw_input("> "))

if num % 2 == 0:
    print "This is not a prime number"

else:
    print "This is a prime number"

When I type '9' it says it's a prime number, which it isn't:当我输入“9”时,它说它是一个质数,它不是:

Type a number
> 9
This is a prime number

Is my code too simple?我的代码太简单了吗? Is there something it doesn't check?有什么不检查的吗?

You're only checking if it is an even number, by checking if it is divisible by 2. But 9 is divisible by 3 so you need to check that also.你只是通过检查它是否能被 2 整除来检查它是否是偶数。但 9 能被 3 整除,所以你也需要检查它。 The easiest way would be to check all numbers up to the square root of the number you're checking for primality.最简单的方法是检查所有数字,直到您检查素数的数字的平方根。

All you are doing here is checking whether or not a number is evenly divisible by 2. Since 9 / 2 = 4.5, it's not evenly divisible by 2 thus going to the else clause.你在这里所做的只是检查一个数字是否能被 2 整除。由于 9 / 2 = 4.5,它不能被 2 整除,因此转到 else 子句。

Here is a condensed, working version of what you probably want:这是您可能想要的精简的工作版本:

def is_prime(a):
    return all(a % i for i in xrange(2, a))

To check if number is prime you have to validate is it devisible by any number in range [2, sqrt(n)].要检查数字是否为素数,您必须验证它是否可以被范围 [2, sqrt(n)] 中的任何数字所除。

Following code does exactly the same:以下代码完全相同:

import math

def is_prime(n):
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True

This method is good for small number, but if n is real big number then you need something faster.这种方法适用于小数字,但如果 n 是真正的大数字,那么你需要更快的东西。 And in this case you can use Miller–Rabin primality test which checks primality with a certain probability.在这种情况下,您可以使用Miller-Rabin 素性检验,它以一定的概率检查素性。

You are checking if a given number is even or not, and 9 is not even so your code prints out "This is a prime number"您正在检查给定数字是否为偶数,而 9 不是偶数,因此您的代码会打印出“这是一个素数”

Please take a look at this Stackoverflow question for a detailed explanation on how to check for prime numbers using Python.请查看这个Stackoverflow 问题,详细了解如何使用 Python 检查素数。

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

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