# Converting decimal numbers to k-decimal with C++

Hello, guys! It’s me! Warotan!

Japanese version.

We sometimes need to convert decimal numbers to the $$k$$-decimal.
I often forget how to implement it and would like to understand, so I decided to write this article.

## Review~$$k$$-decimal numbers

First, we breefly review $$k$$-decimal numbers.
Given any natural number $$N$$, we write it as $${a_{l}a_{l-1}\cdots a_{0}}_{\left(k\right)}$$ in $$k$$-decimal form,

$$\begin{eqnarray} N &=& \sum_{i = 0}^{l}a_{i}k^{i} \\ &=& a_{0}\times k^0+a_{1}\times k+a_{2}\times k^{2}+\cdots +a_{l}\times k^{l} \end{eqnarray}$$

For example, 11 in a decimal number,

$$\begin{eqnarray} 11 = 1\times 10^0+1\times 10 \end{eqnarray}$$

is $$1011_{left(2\right)}$$ in 2-decimal and this represents

$$\begin{eqnarray} 11 = 1\times 2^0+1\times 2+0\times 2^2+1\times 2^3 \end{eqnarray}$$

Also $$102_{\left(3\right)}$$ in 3-decimal and

$$\begin{eqnarray} 11 = 2\times 3^0+0\times 3^{1}+1\times 3^{2} \end{eqnarray}$$

After all, the $$a_{i}$$ in the form of $${a_{l}a_{l-1}\cdots a_{0}}_{\left(k\right)}$$ in $$k$$-decimal one means the coefficients when we divide the given natural number $$N$$ into the sum.

## Idea to convert to $$k$$-decimal numbers

The following equation is important when we convert decimal numbers to the $$k$$-decimal,

$$\begin{eqnarray} N &=& \sum_{i = 0}^{l}a_{i}k^{i} \\ &=& a_{0}\times k^0+a_{1}\times k+a_{2}\times k^{2}+\cdots +a_{l}\times k^{l} \end{eqnarray}$$

In c++, fractions are truncated in division between integers.
Therefore, as the above equation shows, to find each $$a_{i}$$, we just need to divide by $$k^{i}$$ and then take the remainder divided by $$k$$.
This is because all terms up to $$k^{i-1}$$ become zero when divided by $$k^{i}$$, and all terms after $$k^{i+1]$$ disapper by considering the remainder by $$k$$ later.

## Implementation example

Along with the above idea, the implementation is going to be like this.

string ten2k(int n, int k){
string s = "";
if(n == 0) return "0";
if(k == 1){
for(int i = 0;i < n;i++) s += '1';
return s;
}
while(n > 0){
s += to_string(n % k);
n /= k;
}
reverse(s.begin(),s.end());

return s;
}

In the while loop, it extracts each digit. The results are in the reversed order, so do reverse function in the last.
Also, when $$k = 1$$, it gets into an endless loop, so I gave it an exception handling.
In addition to that, $$n = 0$$ case is implemented as an exception because it returns a null string.

## Summary

Now, that’s all what I wanted to write.

This time, I introduced how to convert decimal numbers to the $$k$$-decimal ones.