Tag: prime

PHP Prime Number Script

Here is a simple little script that will determine if a number is prime or not. Just submit the function through with the parameter number as the integer you want to determine – is prime or not.

Syntax

[code lang=”php”]
is_prime(number);
[/code]

Here is the function’s definition:

[code lang=”php”]
function is_prime($num=0)
{

$num = (int)$num; // Make sure it’s an integer.
if($num > 0)
{
$count = 0;
$half = round($num / 2);

for($i=2;$i<=$half;$i++) // Check the remainder from 2 to the half point. { if(($num % $i) == 0) // Remainder is 0, it is divisible. Not a prime number. { $count++; // Increase count of divisible numbers. } } if($count > 0)
{
return false;
} else {
return true;
}
} else {

return false;

}

}
[/code]

Examples:

[code]
is_prime(10);
is_prime(3);
is_prime(109);
[/code]

[code]
false
true
true
[/code]

Basically our script here takes a parameter, makes sure it is an integer greaterĀ  than 0, then divides it by each number from 2 to half way to that number. So if our number was 7 the script would divide 7 by 2, 3, 4. The half mark is rounded to the nearest whole number. Since a remainder exists from each of these divisions, the number is declared as prime.

Click here to demo the script!

Click here to download this script!

Filed under: ScriptsTagged with: , , ,