This function loops through all integer numbers between $start
and $end
. If the square root of the number is equal to its integer part, then $count
is increased by 1.
function countSquares($start, $end)
{
$count = 0;
for($n=$start;$n<=$end;$n++)
{
if(pow($n, 0.5) == intval(pow($n, 0.5)))
{
//echo "$n<br>";
$count++;
}
}
return $count;
}
echo countSquares(4, 17);
However this first function is quite slow when used with large numbers.
This other function does the job much more quickly, and the code is also much shorter.
The number of integer square roots between $start
and $end
is obtained by subtracting the number of integer square roots between 0
and $end
to the number of integer square roots between 0
and $start-1
. (I use $start-1
because your interval includes the starting number)
function countSquares2($start, $end)
{
return floor(pow($end, 0.5)) - floor(pow($start-1, 0.5));
}
echo countSquares2(1000000, 10000000);