How to Check Whether a Number is Prime in PHP
Imagine a given number and you want to check whether it is prime or not with PHP.
Below, we will represent two methods: a simple method and a more efficient one.
Read on to explore them.
Simple Solution
Let’s start with a simpler solution. It considers iterating through all the numbers from 2 to n / 2 for each number checking whether it divides n.
After finding any number that divides, false should be returned, otherwise, true.
The implementation of this solution is below:
<?php
// PHP code for checking if a number is prime or not
// function for checking the number is Prime or not
function primeCheck($number)
{
if ($number == 1) {
return false;
}
for ($i = 2; $i <= $number / 2; $i++) {
if ($number % $i == 0) {
return false;
}
}
return true;
}
// Driver Code
$number = 31;
if (primeCheck($number)) {
echo "Prime";
} else {
echo "Not Prime";
}
The output of the code is as follows:
Prime
A Complex and Efficient Method
Now, let’s explore a more complicated but much more efficient solution.
To implement that solution, it is necessary to optimize the first approach by checking sqrt(n) instead of n. The reason is that a larger factor of n should be multiple of a smaller factor, which has been checked.
The demonstration of this solution is below:
<?php
// PHP code for checking if a number is prime or Not
// function for checking if the number is Prime or Not
function primeCheck($number)
{
if ($number == 1 || $number % 2 == 0) {
return false;
}
for ($i = 3; $i <= sqrt($number); $i += 2) {
if ($number % $i == 0) {
return false;
}
}
return true;
}
// Driver Code
$number = 31;
if (primeCheck($number)) {
echo "Prime";
} else {
echo "Not Prime";
}
Prime
Defining prime Numbers
These numbers are considered unique in comparison with other series of numbers. The logic of prime numbers is the same regardless of the programming language. Only the syntax of a prime number can vary.