1

I have a function, that, given two integers A and B, return the number of whole squares within the interval [A..B] (both ends included)

For example, given $A = 4 and $B = 17, the function should return 3, because there are three squares of integers in the interval [4..17]. namely 4 = 2*, 9 = 3* and 14 = 4*

How would I get a number of square numbers up to the number?

Cleggy1012
  • 21
  • 6

2 Answers2

1

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);
Jocelyn
  • 10,871
  • 10
  • 43
  • 58
  • Really nice logic in `countSquares2`! To become an even better answer, you could explain more mathematical details, why `floor(pow($float_num, 0.5))` is the number of squares from 0. It is not necessarily obvious to people with a lower mathematical background. Explanation could even start at the point, that the power of 0.5 actually is the square root. – Quasimodo's clone May 03 '17 at 08:01
  • PS: I didn't test it in PHP. What is the behavior when it is invoked with negative arguments? Consider to sanitize inputs - also when end is less than start. – Quasimodo's clone May 03 '17 at 08:12
0

Or you could do it by using sqrt function:

function getSquaresInRange($a, $b){
    return floor(sqrt($b)) - ceil(sqrt($a)) + 1;
}
Rwakos
  • 71
  • 3