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. Here, we represent two methods: a simple method and a more efficient one.
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.
Before getting to the solution, try your approach on {IDE}.
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 evenly.
After finding any number that divides, false should be returned, otherwise, true.
The implementation of this solution is below:
php check number is prime or not
<?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 < 2) {
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:
PrimeA 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 code to check if a number is prime
<?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 < 2) {
return false;
}
if ($number == 2) {
return true;
}
if ($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";
}PrimeDefining prime Numbers
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The underlying logic for checking primality remains the same across programming languages; only the syntax changes.