PHP math calculation really slow -
so wrote script can enter number , program find highest prime number in range. problem in php, calculation slow larger numbers, compared javascript version, exact same thing faster.
//here php code: <form> <input type="text" name="input"> </form> <?php $input = $_get['input']; function prime($num) { if($num < 2) return false; ($i = 2; $i < $num; $i++) { if($num % $i == 0) return false; } return true; } for($i = $input; $i > 0; $i--) { if(prime($i)) echo $i; if(prime($i)) exit(); } }
here javascript variant:
<html> <script> var input = prompt("enter number"); function prime(num) { (var = 2; < num; i++) { if(num % == 0) { return false; } } return true; } for(var = input; > 0; i--){ if(prime(i)){ document.write(i); } if(prime(i)){ exit(); p.thisbreaksthecode(); } } </script> </html>
for javascript code, finding highest prime in 99999999 takes 1.5 seconds. however, in php takes whopping 20 seconds. considering fact apart syntax, 2 codes identical. tells me wrong. reason slow calculation speed? because of way php works? how can fix it?
what reason slow calculation speed? because of way php works?
probably; php doesn't (currently) jit optimisations, running tight loops painful.
how can fix it?
by picking better algorithm:
// https://en.wikipedia.org/wiki/primality_test#php_implementation function isprime($n) { if ($n <= 3) { return $n > 1; } else if ($n % 2 === 0 || $n % 3 === 0) { return false; } else { ($i = 5; $i * $i <= $n; $i += 6) { if ($n % $i === 0 || $n % ($i + 2) === 0) { return false; } } return true; } }
for current input runs 500x faster.
Comments
Post a Comment