So I wrote a script where you can enter a number and the program will find the highest prime number in that range. The problem is that in PHP, this calculation is really slow with larger numbers, as compared to my JavaScript version, which is the exact same thing but much faster.
//Here Is the PHP code:
<form>
<input type="text" name="input">
</form>
<?php
$input = $_GET['input'];
function Prime($num)
{
if($num < 2)
return false;
for ($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 is the JavaScript variant:
<html>
<script>
var input = prompt("Enter The Number");
function Prime(num) {
for (var i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
for(var i = input; i > 0; i--){
if(Prime(i)){
document.write(i);
}
if(Prime(i)){
exit();
p.thisbreaksthecode();
}
}
</script>
</html>
For the JavaScript code, finding the highest prime in 99999999 takes 1.5 seconds. However, in PHP it takes a whopping 20 seconds. Considering the fact that apart from syntax, the two codes are exactly identical. This tells me something is wrong. What could be the reason for this slow calculation speed? Is it because of the way PHP works? How can I fix it?
What could be the reason for this slow calculation speed? Is it because of the way PHP works?
Probably; PHP doesn't (currently) do JIT optimisations, so running tight loops like that will be very painful.
How can I fix it?
By picking a 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 {
for ($i = 5; $i * $i <= $n; $i += 6) {
if ($n % $i === 0 || $n % ($i + 2) === 0) {
return false;
}
}
return true;
}
}
For your current input it runs 500x faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With