Recursive method to calculate log

13,679

Solution 1

If the format MUST be like this:

int log(int b, int n ) {
    if <<enter base case>> {
        return 1;
    } else {
        return <<enter action case>> ;
    }
}

Then the safest method (that I can come up with) would be:

int log(int b, int n ) {
    if (n <= b) {
        return 1;
    } else {
        return log(b, n/b)+1 ;

    }
}

Solution 2

A better solution in my opinion would be

int log(int b, int n ) {
    if (b > n) {
        return 0;
    } else {
        return 1 + log(b, n/b);
    }
}

This returns the log base b of n rounded down to an integer, and has more consistency with inexact results than the other answer.

e.g. log(2,6)=2 ; log(2,7)=2 ; log(2,8)=3 ; log(2,9)=3

Though, it still doesn't handle things like b < 2 or cases where the result would be negative.

Share:
13,679
Admin
Author by

Admin

Updated on August 02, 2022

Comments

  • Admin
    Admin over 1 year

    I did the following to calculate recursive logarithm:(b is the base of log here)

    int log(int b, int n) {
      if (n/b == 1) {
        return 1;
      } else {
        return log(b, n/b) + 1;
      }
    }
    

    However, it's wrong.I'm doing it from the openDSA interactive platform.The original question is the following:

    For function "log", write the missing base case condition and the recursive call. This function computes the log of "n" to the base "b". As an example: log 8 to the base 2 equals 3 since 8 = 222. We can find this by dividing 8 by 2 until we reach 1, and we count the number of divisions we made. You should assume that "n" is exactly "b" to some integer power.

    int log(int b, int n) {
      if /* Missing base case condition */ {
        return 1;
      } else {
        return /* Missing a Recursive case action */;
      }
    }
    

    My code is incorrect.I'm getting infinite recursion.