Consider a function $R: \mathbb N \to \mathbb N,$ $R(n)$ is the distance to the next square greater or equal to $n$.
For example, $R(5)=4$ and $R(16)=0.$
Function $R$ has two fixed points, $0$ and $2$. I ask, which numbers, under iterations of $R$, ultimately become $2$.
Simple checking gives a list which begins $L = \{2,7,14,18,23,29,34,42,\dots\}.$
For example $R(18)=7$ and $R(7)=2$.
I can give a procedure which gives all numbers in L and only those numbers:
Start with $L_1 = \{2\}.$ Then take 3^2 and subtract from it such numbers in $L_1$ which are smaller than $2*3-1=5$. There is only one, $2$, and $9-2 = 7$ and add this to $L_1$ and we get $L_2 = \{2,7\}.$
Then consider $4^2$ and do the same as above. There is only one number in $L_2$ smaller than $2*4-1=7$, hence next number in $L$ is $4^2-2=14$ and thus $L_3 = \{2,7,14\}.$
Now look at $5^2$ and note that $L_3$ has two numbers smaller than $2*5-1=9$, $2$ and $7$. $25-2=23$ and $25-7=18$. Add these to $L_3$ and get $L_4= \{2,7,14,18,23\}$.
And so on. To get from $L_n$ to $L_{n+1}$, subtract from $(n+2)^2$ all numbers in $L_n$ that are smaller than $2n-1$ and add the results to list in order to get the next iteration.
However, this seems very cumbersome. How would this be written as a recurrence relation or is there a formula for numbers in $L$?
Notes: $$k \in L \wedge k<2n-1 \implies R(n^2-k)=k.$$ We need $k<2n-1$ because $n^2-(n-1)^2=2n-1$, thus subtracting anything larger would mean the distance to the next square would be smaller than the number subtracted.