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"; } ?>
Leave a Reply