This code is taking like 15mins to complete, is there anyway it could be optimized?
<?php
$base = 99;
$results = 1975;
$goal = 1000001;
while ($results <= $goal)
{
for ( $i=0; $i <= $base; $i++ )
{
for ( $j=$i+1; $j < $base ; $j++ )
{
$hypo = sqrt(( pow($i + $j, 2) )+ pow($base, 2));
if ($hypo == (int) $hypo )
{
if ($results == $goal)
{
echo $i, ' ', $j, ' ',$base , '
';
break 3;
}
else
{
$results++;
}
}
}
}
$base++;
}
echo $base;
?>
In a tight loop that’s iterated so many times, preincrement is going to be faster than postincrement.
And calling pow() has the overheads of the function call, faster to do the math directly.
That still won’t be fast because of the sheer number of iterations, but those two minor changes should reduce the time taken quite significantly… think about 50%-75% faster.
But if you explain what you’re actually trying to do – it looks like you’re trying to work out pythagorean triangle numbers – perhaps there are more efficient methods than brute force.
EDIT
Performance when executed with $goal = 10001:
SO you can see that postincrement -> preincrement reduces by about 0.05 seconds, but replacing the call to pow() by doing the math directly makes the most significant difference.