PHP | Check if a number is prime
Last Updated :
15 May, 2025
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The smallest prime number is 2, which is the only even prime number. All other even numbers are not prime because they are divisible by 2.
- 2 is prime because it can only be divided by 1 and 2.
- 3 is prime because it can only be divided by 1 and 3.
- 4 is not prime because it is divisible by 1, 2, and 4.
PHP Code to Check if a Number is Prime
Below are the following approaches by which we can check if a number is prime or not in PHP:
1. Basic Approach
Let's start with a simple approach where we check divisibility for every number from 2 up to n-1
. This method works, but is not efficient for large numbers.
PHP
<?php
function isPrime($num) {
if ($num <= 1) {
return false;
}
for ($i = 2; $i < $num; $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}
$number = 61;
if (isPrime($number)) {
echo "$number is a prime number.";
} else {
echo "$number is not a prime number.";
}
?>
Output61 is a prime number.
In this example:
- The function
isPrime()
takes an integer $num
as input. - We check if the number is less than or equal to 1. If so, it's not prime.
- The
for
loop checks if the number is divisible by any number from 2 to $num-1
. - If a divisor is found, the function returns
false
indicating the number is not prime. - If no divisors are found, the function returns
true
indicating the number is prime.
2. Optimized Approach (Using Square Root)
A more efficient approach is to check divisibility only up to the square root of the number. This reduces the number of iterations, especially for large numbers.
PHP
<?php
function primeCheck($number){
if ($number == 1)
return 0;
for ($i = 2; $i <= sqrt($number); $i++){
if ($number % $i == 0)
return 0;
}
return 1;
}
$number = 12;
$flag = primeCheck($number);
if ($flag == 1)
echo "Prime";
else
echo "Not Prime"
?>
In this example:
- This method improves efficiency by limiting the loop to only check divisibility up to
sqrt(num)
. - If
num
is divisible by any number within this range, it is not prime. - The
sqrt()
function computes the square root of a number, and we check divisibility up to that value.
Time Complexity
- Method 1 (Basic): The time complexity of the basic method is O(n), where
n
is the number being checked. - Method 2 (Optimized): The optimized method has a time complexity of O(√n) because it checks divisibility only up to the square root of the number.
Thus, Method 2 is much more efficient, especially for large numbers.
Conclusion
In this article, we explored how to check if a number is prime in PHP. We began with a basic approach, then moved on to an optimized solution that limits the number of iterations by checking divisibility only up to the square root of the number. By handling edge cases and improving efficiency, we can check the primality of both small and large numbers effectively.