Hello, guys! It’s me! Warotan!
So…Who are you?→ABOUT MEJ
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,
For example, 11 in a decimal number,
is \(1011_{left(2\right)}\) in 2-decimal and this represents
Also \(102_{\left(3\right)}\) in 3-decimal and
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,
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.
(2021.10.12. Added)
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.
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)