0
$\begingroup$

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?

$\endgroup$
1
$\begingroup$

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.

The same goes on with every other number system.

$\endgroup$
  • $\begingroup$ yes I completely understand that. But my question is why does is the algorithm mathematically correct (intuitively, perhaps)? $\endgroup$ – jaynp Feb 23 '14 at 23:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.