Looking for a way to find prime numbers in php? I wfound one perl solution here, but it wasn’t perl magic – it was power of regular expressions.
Please find code below which will be self-explanatory.
<?php
/**
* Function checks if given number is prime
*
* @param integer $n
* @return boolean
*/
function isPrime($n) {
return (!preg_match(‘/^1?$|^(11+?)\1+$/x’, str_repeat(’1′, intval($n)))) ;
}
for ($n=0;$n<100;$n++) {
echo “Number {$n} is “.(isPrime($n) ? ‘prime’ : ‘not prime’).”<br/>\n”;
}
?>

Pingback: Tweets that mention Prime numbers in PHP – quick and efficient way | PHP 4u Web developer - 代码的简化 -- Topsy.com