VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-compute-log-a-to-any-base-b-logb-a/

⇱ Program to compute log a to any base b (logb a) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to compute log a to any base b (logb a)

Last Updated : 12 Jul, 2025

Given two integers a and b, the task is to find the log of a to any base b, i.e. logb a.
Examples:

Input: a = 3, b = 2
Output: 1
Input: a = 256, b = 4
Output: 4


  1. Find the log of a to the base 2 with the help of log2() method 
  2. Find the log of b to the base 2 with the help of log2() method 
  3. Divide the computed log a from the log b to get the logb a, i.e, [latex]\LARGE log_{b}\text{ } a = \frac{log\text{ }a}{log\text{ }b}[/latex]


Below is the implementation of the above approach 


Output
1
4

Time Complexity: O(logba)
Auxiliary Space: O(1)

  1. Recursively divide a by b till a is greater than b. 
  2. Count the number of times the divide is possible. This is the log of a to the base b, i.e. logb a

Below is the implementation of the above approach 


Output
1
4

Time Complexity: O(logba)
Auxiliary Space: O(logba) Space required for recursive call stack

Approach:

The approach is to repeatedly divide the given number 'a' by the base 'b' until 'a' becomes less than or equal to 1. In each division, we increment the answer by 1. Finally, we return the answer which represents the logarithm of 'a' to the base 'b'.

  • Initialize a variable 'ans' to 0.
  • Repeat the following steps until 'a' becomes less than or equal to 1:
    a. Divide 'a' by 'b'.
    b. Increment 'ans' by 1.
  • Return 'ans' as the result.

Output
1
4

Time Complexity: O(log a), as in each iteration, 'a' is divided by 'b'.
Space Complexity:  O(1), as only a constant amount of extra space is required for storing the 'ans' variable.

Comment
Article Tags:
Article Tags: