[英]Prime number checker function is faulty
I wrote a function to calculate whether or not a number is prime, but try as it might, it just seems unable to give the correct response. 我写了一个函数来计算一个数字是否为素数,但尽可能尝试,它似乎无法给出正确的响应。 It also prints the n value that is being incremented.
它还会打印正在递增的n值。 Here is the code for the function (in Python, by the way):
这是函数的代码(顺便说一句,在Python中):
def isPrime(x):
for n in range(1, x):
print n
if x % n == 0:
return False
return True
If I input 如果我输入
isPrime(17)
the function returns 函数返回
1
False
What is going wrong here? 这里出了什么问题?
Every number is divisible by 1 and itself . 每个数字都可以被1和它自身整除 。 A prime number is a natural number that has no positive divisors other than 1 and itself.
素数是比1和它本身外没有其他积极的除数自然数。 Therefore, if you start your for-loop with 1, every number
x
will pass the condition x % 1 == 0
in the first iteration, returning False
. 因此,如果以1开始for循环,则每个数字
x
将在第一次迭代中传递条件x % 1 == 0
,返回False
。
To fix it, you need to start your loop with 2 instead of 1. Also, as a side-note, you just need to loop from 2 to sqrt(x)
, since if there exists a number q > sqrt(x)
that divides x
, then there must also be a number p = x / q
which also divides x
, and p < sqrt(x)
. 要修复它,你需要以2而不是1开始循环。另外,作为旁注,你只需要从2循环到
sqrt(x)
,因为如果存在数q > sqrt(x)
那么除了x
,那么还必须有一个数p = x / q
,它也除x
和p < sqrt(x)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.