user1860447
user1860447

Reputation: 1436

to find a prime number in java

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

Upvotes: 0

Views: 211

Answers (2)

Stefanel S
Stefanel S

Reputation: 45

This is a logical rule : there is no point to search for other divisors once you pass the square root because at that point your "new" divisors" will be lower than your square root.

Divisors come in pairs: 10 = 2 x 5. Both 2 and 5 are divisors. In each pair one is <= the square root, and the other is >= the square root. 2 <= sqrt(10); 5 >= sqrt(10). Once you have found the 2, there is no need to carry on searching for the 5. 5 = 10 / 2.

eg : 100 : you check for 2,3,5,7,9, and you stop because if you check for next one (11), 100/11 is 9 and you already checked for 9. You stop at the square root.

Upvotes: 4

div
div

Reputation: 573

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

h * c = n
and since h > sqrt(n) and h * c = sqrt(n) * sqrt(n)
c < sqrt(n).

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

i*i < n

is imposed.

Upvotes: 1

Related Questions