问题
How we can use sqrt(n)
instead of n/2
in this code? Is it correct to use sqrt(n)
?
static boolean isPrime(long n)
{
if(n<=1) return false;
double limit = Math.sqrt(n);
for(long i = 2; i <= limit; i++)
{
if(n%i==0) return false;
}
return true;
}
回答1:
if n
is not a prime, say n = p * q
, then p
and q
cannot be both greater than sqrt(n)
(otherwise p*q
would be greater than n
)
回答2:
The shown algorithm checks for every integer between 2 and sqrt(n) if n is divisible by it.
If n was divisible by a number greater than sqrt(n), say a
, then there would be a factor b
so that a * b = n
and b < a
. In this case the algorithm will find b "first" and see that n is not prime.
Therefore it is not necessary to check any number > sqrt(n).
回答3:
Perhaps the code would be more understandable (and faster) if you wouldn't use sqrt().
for (long i = 2; i*i <= n; i = (i==2) ? 3 : i+2) {
....
}
Consider ii > n, and n is divisible by i, so that n/i = m. Then m must be smaller than i. But this means your loop must have encountered m earlier already, and found that n is divisible by m. So this means that you find all divisors of n by looping through the range 2..k, where kk <= n.
If you compute a list of prime numbers, you can also take advantage of the fact that if n is not prime, it must be divisible by a prime number. Hence it suffices to check only prime numbers lower or equal than sqrt(n). Since there are much less prime numbers than ordinary numbers in the range, your code will run even faster. You can take the prime numbers from the part of the list you have already computed.
来源:https://stackoverflow.com/questions/21383349/why-we-can-use-sqrtn-instead-of-n-2-as-an-upper-bound-while-finding-prime-numb