C++ Recursion – Logarithm

Finding the logarithm of a number given a base

Below is an example of how to determine the logarithm of a number of base 2 and then of any base. The logarithm of a number using a given base is power to which the base must be raised to result in the number. This tutorial assumes you understand C++ Recursion and the C++ Recursion – Power function.

Example of finding the logarithm given a base

You could find the base using two different methods.

  1. Multiply the base by itself until you receive the number.
  2. Divide the number by the base, and repeat until you result in 1. For this method the result is the number of computations to get to 1.

[pmath]logBase2(8) = 3
2 * 2 * 2 = 8

Method 2:
8/2 = 4
4/2 = 2
2/2 = 1

logBaseN(16,2) = 4
2 * 2 * 2 * 2 = 16

Method 2:
16/2 = 8
8/2 = 4
4/2 = 2
2/2 = 1
[/pmath]

Recursive version of logBase2 function

Given the example above, could you come up with a logBase2 recursive function? Let’s try using the 2nd method described above. So what would be our base case and header?

Header and base case for logBase2 function

Below is the header for the logBase2 function. We only need one parameter.

int logBase2(int num) { 


What about our base case? By using our second method we want to stop dividing our number by our base 2 until we result in 1.

int logBase2(int num) { 

      if ( num == 1 )
           return 0; 

LogBase2 Recursive Function

Looking back at our second method, we count the number of computations until our number is 1. Let’s do this. We also break down the problem by diving our number by 2 at each iteration.

int logBase2(int num) { 

      if ( num == 1 )
           return 0; 

      return 1 + logBase2(num/2);

}


Yes, that’s it. This recursive function will return the number which is the power to the base to get to our number.

Recursive version of logBaseN function

Our previous function took care of logBase2 values. What about logBaseN values? This simply means you pass in the base as well. This addition should be trivial.

LogBase2 Recursive Function

Now, we are simply modifying our previous function but this time around we are also passing in the base.

int logBaseN(int num, int base) { 

      if ( num == 1 )
           return 0; 

      return 1 + logBase2(num/base, base);

}


Going further

  1. 1. Can you take care of error detection? What if a user puts in erroneous numbers or bases?

Tags: , , , , , , , ,