シェアする

  • このエントリーをはてなブックマークに追加

Converting decimal numbers to k-decimal with C++

シェアする

  • このエントリーをはてなブックマークに追加

Hello, guys! It’s me! Warotan!
So…Who are you?→ABOUT MEJ

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.

I write similar articles and will add contents, so please read more other articles.

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(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.

Summary

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

This time, I introduced how to convert decimal numbers to the \(k\)-decimal ones.

Thank you for reading and please spread this blog if you like.

If you have any comment, please let me know from the e-mail address below or the CONTACT on the menu bar.
tsunetthi(at)gmail.com
Please change (at) to @.

Or you can also contact me via twitter (@warotan3)

シェアする

  • このエントリーをはてなブックマークに追加

フォローする