Finding the smallest number whose sum of the digits is equal to a given N I am solving a question on Geeks For Geeks. The problem is to find the smallest number whose sum is equal to the given N. The solution is being determined by the formula Formula But I don't understand how are we reaching at this formula?
 A: The formula given on the site is
$$(N \bmod 9 + 1)\cdot 10^{\left\lfloor \dfrac{N}{9}\right\rfloor}- 1$$
Meaning that whatever the number $N$, we want to stick as many $9$s as possible in the number (to reach $N$ faster). For that we simply divide $N$ by $9$, which gives the number of $9$s to use, and the final digit is the remainder of that $\dfrac{N}{9}$, or $N \bmod 9$.
We could put that final remainder digit anywhere, like $99399$, but since the smallest number is requested, that digit will be leading the number (like $39999$).
For $N=31$, we have $N=31=3\cdot 9+4$, so we know  we need three $9$, and the remainder, $4$. The number would be $4999$.
The formula above does the same thing in one single calculation. Instead of building the number by piling the $9s$, it finds the resulting number $+1$, that is a power of $10$ multiplied by a digit, and then subtract $1$ to reach the solution. For $N=31$, that would be $5000-1$.

*

*the $(N \bmod 9+1)$ finds the remainder, and adds one to it ($5$ in the example)

*the $10^{\left\lfloor \dfrac{N}{9} \right\rfloor}$ gives the number of $0s$ to (powers of $10$) to give to that number, $\left\lfloor \dfrac{N}{9} \right\rfloor$ gives the integer part of $N/9$. ($3$ in the example)

*finally subtract $1$ ($5000-1$ in the example)

