计算日志的递归方法

时间:2016-06-02 04:46:40

标签: java recursion

我做了以下计算递归对数:( b是这里记录的基础)

    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 = 2*2*2. 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.

1
int log(int b, int n ) {
2
  if <<Missing base case condition>> {
3
    return 1;
4
  } else {
5
    return <<Missing a Recursive case action>>
6
  }
7
}

然而,这是错误的。我是在openDSA互动平台上做的。原来的问题如下:

{{1}}

我的代码不正确。我得到了无限的递归。

2 个答案:

答案 0 :(得分:2)

如果格式必须是这样的:

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

那么最安全的方法(我可以提出)将是:

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

    }
}

答案 1 :(得分:0)

我认为更好的解决方案是

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

这将返回n的对数底数b,将其四舍五入为整数,并且与不精确的结果相比,与其他答案相比具有更大的一致性。

例如log(2,6)= 2; log(2,7)= 2; log(2,8)= 3; log(2,9)= 3

尽管如此,它仍然不能处理b <2或结果为负的情况。

相关问题