DEV Community

Cover image for Simple and interesting way to convert from base 10 using recursion
Rusu Emanuel
Rusu Emanuel

Posted on • Updated on

Simple and interesting way to convert from base 10 using recursion

👋Heeelloo everybody! 🔥🚀

As you read above, I will show you a really excellent and exciting way to convert a number from base 10 to smaller bases using the power of recursion.💪


Before we jump into the code, I will list some observations to make sure that you understand what input the program can take.

  • Variables are declared: unsigned long long for the input number, so you can enter any strict positive number till 2^64 - 1 and I used unsigned short for the base you can choose to convert to. You can choose between base 2 till base 10.

  • I focused on the idea rather than on a real-world scenario where I must consider validations and other stuff. Of course, this code can be extended to support bases up from 10 and things such as quick conversions, but I will cover these things in the future.

  • I have used C++ programming language.


So, what is the idea ?🤔🤔

Commonly, we repetitively divide the number by the base until the number becomes zero, then we take every rest of the divisions in reverse order, and this is the new number. This process is tough, and it requires extra variables.

Recursion does a good job here. We recursively call the same function with the new number divided until we hit the base case(the number becomes 0), then stack frames from recursion are resumed beginning from the end, so in reverse order. Now, in memory, every stack frame resulting from function calls contains a number, and the only thing we have to do is print [that number] % [the base] as the last instruction for every stack frame.


Here is the code🔥

#include <iostream>
using namespace std;


void Convert(unsigned long long Number, const unsigned short BaseToConvert)
{
    if (Number)
    {
        Convert(Number / BaseToConvert, BaseToConvert);
        cout << Number % BaseToConvert;
    }
}


int main()
{
    unsigned long long number; cout << "Number to convert: "; cin >> number;

    unsigned short baseToConvert; cout << "\nNew base: "; cin >> baseToConvert;

    cout << "\nNumber converted: "; Convert(number, baseToConvert); cout << '\n';
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Thank you for reading !😃
I hope you enjoyed reading and found this interesting.


  • Emanuel Rusu

  • You can visit my GitHub

  • Or you can find me on Linkedin

  • Next topic: Algorithms for primes number - introduction

  • See you next time ! 👋

Discussion (0)