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.
- Multiply the base by itself until you receive the number.
- 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.
logBase2(8) = 3
2 * 2 * 2 = 8Method 2:
8/2 = 4
4/2 = 2
2/2 = 1logBaseN(16,2) = 4
2 * 2 * 2 * 2 = 16Method 2:
16/2 = 8
8/2 = 4
4/2 = 2
2/2 = 1
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?
Read more »


