Why we can use sqrt(n) instead of n/2 as an upper bound while finding prime numbers? [duplicate]
问题 This question already has answers here : Why do we check up to the square root of a prime number to determine if it is prime? (13 answers) Closed 7 years ago . 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)