This code defines a function `isPrime` that determines whether the...
This code defines a function isPrime
that determines whether the input integer n
is a prime number.
Here's a step-by-step explanation of how this code works:
-
Handle small numbers:
if (n <= 1) { return false; }
- Any number less than or equal to 1 is not prime, so the function immediately returns
false
.
if (n <= 3) { return true; }
- Numbers 2 and 3 are prime, so the function immediately returns
true
for these cases.
- Any number less than or equal to 1 is not prime, so the function immediately returns
-
Handle divisibility by 2 or 3:
if (n % 2 == 0 || n % 3 == 0) { return false; }
- If
n
is divisible by 2 or 3, it is not prime, and the function returnsfalse
.
- If
-
Iterate through larger potential divisors:
for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } }
-
Starting from 5, the loop checks divisors up to the square root of
n
. -
The loop increments
i
by 6 each iteration, effectively checking divisors that are:i
(e.g., 5, 11, 17, ...)i + 2
(e.g., 7, 13, 19, ...)
-
This optimization works because, beyond 2 and 3, any prime number is of the form
6k ± 1
(for integerk
). -
If
n
is divisible by any of these numbers, it is not prime, and the function returnsfalse
.
-
-
Return true if no divisors are found:
return true;
- If none of the above checks indicate that the number is composite, the function concludes that
n
is prime and returnstrue
.
- If none of the above checks indicate that the number is composite, the function concludes that
Summary:
The function efficiently checks whether a number n
is prime or not, using optimizations to minimize unnecessary divisibility checks. It first handles simple base cases, eliminates even numbers and multiples of 3, and iterates over potential divisors in the form of 6k ± 1
up to the square root of n
.