要检验一个数是不是质数,为什么我们要检验它是否只能被这个数的平方根整除?
当前回答
对于任意数n,求因数的一种方法是求根号p:
sqrt(n) = p
当然,如果我们用p乘以它自己,就会得到n:
p*p = n
可以改写为:
a*b = n
其中p = a = b,如果a增加,则b减少,以保持a*b = n,因此p为上限。
Update: I am re-reading this answer again today and it became clearer to me more. The value p does not necessarily mean an integer because if it is, then n would not be a prime. So, p could be a real number (ie, with fractions). And instead of going through the whole range of n, now we only need to go through the whole range of p. The other p is a mirror copy so in effect we halve the range. And then, now I am seeing that we can actually continue re-doing the square root and doing it to p to further half the range.
其他回答
其实就是基本的因式分解和平方根。
它可能看起来很抽象,但实际上它只是在于这样一个事实,即一个非质数的最大可能阶乘必须是它的平方根,因为:
sqrroot(n) * sqrroot(n) = n。
鉴于此,如果任何大于1且小于或大于√(n)的整数能被n整除,则n不可能是质数。
伪代码示例:
i = 2;
is_prime = true;
while loop (i <= sqrroot(n))
{
if (n % i == 0)
{
is_prime = false;
exit while;
}
++i;
}
假设m =根号n,那么m × m = n。如果n不是质数,那么n可以写成n = a × b,所以m × m = a × b。注意,m是实数,而n、a和b是自然数。
现在有三种情况:
A > m⇒b < m ⇒A = m, b = m A < m⇒b > m
在这三种情况下,min(a, b)≤m。因此,如果我们搜索到m,我们一定会找到n的至少一个因子,这足以证明n不是质数。
任何合数都是质数的乘积。
假设n = p1 * p2,其中p2 > p1,它们都是质数。
如果n % p1 === 0,则n是一个合数。
如果n % p2 === 0,那么猜猜n % p1 === 0 !
因此,如果n % p2 === 0,同时n % p1 !== 0,这是不可能的。 换句话说,如果一个合数n能被 p2、p3……PI(较大因子)也要除以最小因子p1。 事实证明,最低因子p1 <= Math.square(n)总是正确的。
因为如果一个因子大于根号n,那么与它相乘等于n的另一个因子必然小于根号n。
假设给定的整数N不是质数,
则N可分解为a和b两个因子,2 <= a, b < N使N = a*b。 显然,它们不能同时大于根号N。
让我们不失一般性地假设a更小。
现在,如果你找不到N的任何除数在[2,根号(N)]范围内,这意味着什么?
这意味着当N <=√(N)时,N在[2,a]中没有任何除数。
因此,a = 1且b = n,因此根据定义,n是素数。
...
如果您不满意,请继续阅读:
(a, b)可能有许多不同的组合。假设它们是:
(a1, b1), (a2, b2), (a3, b3), ....., (ak, bk)。在不失一般性的前提下,假设ai < bi, 1<= i <=k。
现在,为了证明N不是质数它足以证明ai都不能被进一步分解。我们还知道ai <=根号N,因此你需要检查根号N,这将涵盖所有ai。这样你就能得出N是不是质数。
...