When you pass a number to the function, first thing is quick check for the case of 1
which is not prime and can divide all other positive integer without remainder. So, this is specially checked case:
if (n == 1) {
return false;
}
Then, in for loop you are checking if given number is divisible with any integer up to half of giving number, which allows us to decide whether it is prime or not. If it is divisible, then it is not prime, return false. The way to check if a number is divisible or not is to use mod operator.
But there is a problem; as @WJS said in the comment section, you do not need to check all the number up to n / 2
, from Wikipedia:
To test the primality of 100 by trial division, consider all the
integer divisors of 100:
2, 4, 5, 10, 20, 25, 50 The largest factor is 100/2 = 50. This is true
for all n: all divisors are less than or equal to n/2. Inspecting the
divisors, it is determined that some of them are redundant. The list
of divisors may be written as:
100 = 2 × 50 = 4 × 25 = 5 × 20 = 10 × 10 = 20 × 5 = 25 × 4 = 50 × 2
which demonstrates the redundancy. Once the divisor 10 is tested,
which is √100, the first divisor is simply the dividend of a previous
divisor. Therefore, testing divisors greater than √n can be
eliminated.
So, your code can be more efficient with following way:
for (int i = 2; i < Math.sqrt(n)+1; i++) {
if (n % i == 0) {
return false;
}
}
Lastly, if you can not divide your number with any number up to its square root, then it means that it is prime, so return true.