I know this question has been answered before, but I didn't quite understand the explanation that was given on that question.
I was doing the 30 days of code on HackerRank, and one of the exercises was to check whether a number is prime or not. Unfortunately, I was not capable of doing it by myself, so I checked the given solution after many attempts. Even after looking at the solutions, I can't understand one of the lines:
// Check for primality using odd numbers from 3 to sqrt(n)
for(int i = 3; i <= sqrt(n); i += 2){
// n is not prime if it is evenly divisible by some 'i' in this range
if( n % i == 0 ){
isPrime = false;
}
}
Why is sqrt(n)
used in the for
loop?