Click Fraud Protection
PHP related blog, freelancer to hire!

Prime numbers in PHP – quick and efficient way

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.

* 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";
1 Comment

    Leave a Reply