How to check whether a number is prime
Short answer
It is enough to check divisors up to the square root of the number:
<?php
function isPrime(int $number): bool
{
if ($number < 2) {
return false;
}
for ($divisor = 2; $divisor * $divisor <= $number; $divisor++) {
if ($number % $divisor === 0) {
return false;
}
}
return true;
}
var_dump(isPrime(97), isPrime(91));Output:
bool(true)
bool(false)All primes up to N
Filter a range with the same function:
<?php
function isPrime(int $number): bool
{
if ($number < 2) {
return false;
}
for ($divisor = 2; $divisor * $divisor <= $number; $divisor++) {
if ($number % $divisor === 0) {
return false;
}
}
return true;
}
echo implode(', ', array_filter(range(1, 30), 'isPrime'));Output:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29Functions used in this recipe
- sqrt — Returns the square root of a number.
- range — Creates an array holding a sequence of values.
- array_filter — Keeps the array elements that pass a test.