I was recently trying to solve a programming problem on hackerrank and the problem description was that given two points $a$ and $b$ I was supposed to find amount of square integers in given range.
For example:
$a = 3$,
$b = 9$
Output: $2$ (because from $3$ to $9$ only $\{4,9\}$ are square ints)
3 4 5 6 7 8 9
However the formula that I used (friend helped) was:
$$\lfloor\sqrt(b)\rfloor - \lceil\sqrt(a)\rceil +1$$
My question is: how does this formula work? What is the concept behind it?
We are looking for all $x\in\mathbb{Z}$ such that $a \leqslant x^2 \leqslant b$ this implies that $\sqrt{a} \leqslant x \leqslant \sqrt{b}$ since $x$ can only be an integer the minimum value of $x$ is the first integer greater than or equal to $\sqrt{a}$ which is $\lceil\sqrt{a}\rceil$ likewise the maximum value of x is the last integer smaller than or equal to $\sqrt{b}$ which is $\lfloor\sqrt{b}\rfloor$. Now if $n$ and $m$ are integers the number of integers between $n$ and $m$ including both $n$ and $m$ is $m-n+1$ so the number of integers between $\lceil\sqrt{a}\rceil$ and $\lfloor\sqrt{b}\rfloor$ is simply $\lfloor\sqrt{b}\rfloor-\lceil\sqrt{a}\rceil+1$