1

What is the rationale behind the below algorithm :

Algorithm to Convert From Decimal To Another Base
Let n be the decimal number.
Let m be the number, initially empty, that we are converting to. We'll be composing it right to left.
Let b be the base of the number we are converting to.
Repeat until n becomes 0
Divide n by b, letting the result be d and the remainder be r.
Write the remainder, r, as the leftmost digit of b.
Let d be the new value of n.

user1718009
  • 303
  • 3
  • 7

1 Answers1

2

Statement: the remainder r is the last digit of the result.

Indeed, separate n into two parts: the part divisible by r and the remainder. We get n = d * b + r where 0 <= r < b.

In base b, the notation is n = c_k * b^k + ... + c_1 * b^1 + c_0 * b^0. Since everything except c_0 * b^0 is divisible by b, the equality r = c_0 follows trivially.


For the remaining digits, rewrite

n = c_k * b^k + ... + c_1 * b^1 + c_0 * b^0

as

n = (c_k * b^{k-1} + ... + c_1 * b^0) * b + c_0 * b^0.

On the other hand,

n = d * b + r.

It immediately follows that

d = c_k * b^{k-1} + ... + c_1 * b^0.

So, to find all digits except the last, we got to solve the same problem but for d < n instead of n. Overall correctness now follows trivially by induction by n.

Gassa
  • 8,546
  • 3
  • 29
  • 49