# Computing digits of number in another base

I would like to program a procedure to convert a number in base 10 to a set of digits in an arbitrary base.

Through empirical testing I see that the procedure involves repeated mod operations and div operations to give the digits in least significant order. i.e.

// Returns list of NUMBER's (>=0) digits in BASE (>=2) in least
// significant to most significant order.

function convertToBase(number, base):
digits = list()
while number != 0:
add (number mod base) to digits
let number := number / base
return digits


But I have little intuition for why this procedure works? Can someone explain?

Let's see how it works for a real example, say when number=125 in decimal.
First digits=list(). Then it adds 125 mod 10 to that, so digits=(5) now, then we perform integer division 125 / 10 that results in number=12.
In the next round, as 12 mod 10=2, we will have digits=(5,2) (if add adds it to the right) and number=12/10=1.
Finally, we end up with digits=(5,2,1), and as the integer division of 1/10 results in 0, the procedure will end.