The invariant I used is:

If a nonnegative integer $x$ is less than $a$ or greater than $b$, then there is NO perfect square that can be added to $x^2$ to produce $n$.