Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP program to check if a number is prime or not
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. To check if a number is prime in PHP, we can create a function that tests for divisibility by all numbers from 2 up to half of the given number.
Example
The following PHP function checks if a number is prime −
<?php
function check_prime($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
echo "It is a prime number";
else
echo "It is a non-prime number";
?>
Output
It is a prime number
How It Works
The check_prime() function works by −
- First checking if the number is 1, which is not considered prime
- Testing divisibility from 2 up to half of the given number
- If any divisor is found, the number is not prime (returns 0)
- If no divisors are found, the number is prime (returns 1)
Testing Multiple Numbers
You can test multiple numbers using an array −
<?php
function check_prime($num)
{
if ($num <= 1)
return 0;
for ($i = 2; $i <= sqrt($num); $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
$numbers = [2, 4, 17, 25, 29];
foreach ($numbers as $num) {
if (check_prime($num))
echo "$num is prime
";
else
echo "$num is not prime
";
}
?>
2 is prime 4 is not prime 17 is prime 25 is not prime 29 is prime
Conclusion
The prime checking algorithm tests divisibility up to the square root of the number for efficiency. This method effectively determines whether a given number is prime by checking for any factors other than 1 and itself.
Advertisements
