I came accros one of the solutions for finding if a number is prime as below :
//checks whether an int is prime or not.
boolean isPrime(int n) {
if (n == 2){
return true;
}
//check if n is a multiple of 2
if (n%2==0){
return false;
}
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
What I am trying to understand is this line of code:
for(int i=3;i*i<=n;i+=2)
how does
i*i<=n
help in determining that the number is prime ?
Thanks
If you find all divisors(including the primes) of n are say a,b,c,d...h.
If a divisor h > sqrt(n) exists, then some divisor c must also exist such that
So, if a divisor greater than sqrt(n) exists than a divisor less than sqrt(n) must also exist and should be able to break the loop before it counts beyond sqrt(n). So, we don't need to count beyond sqrt(n), hence the condition
is imposed.