为方法编写递归关系
我有一些代码,需要为其编写一个递归关系。该代码仅计算 2 的 n 次方。 任何帮助表示赞赏。
public static int two(int n) {
if (n==0) {
return 1;
} else if (n%2 == 0) {
int x = two(n/2);
return x*x;
} else {
return 2 * two(n-1)
}
I have a bit of code and need to write a recurrence relation for it. The code simply calculates 2 raised to the nth power.
Any help is appreciated.
public static int two(int n) {
if (n==0) {
return 1;
} else if (n%2 == 0) {
int x = two(n/2);
return x*x;
} else {
return 2 * two(n-1)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数的表述几乎是递推关系。基本上,您需要做的就是执行变量更改,以便递归中
two
的参数为n
。例如,采用以下斐波那契函数:您不会想使用该实现,因为它的效率非常低,但它使编写递归关系变得容易:
使用斐波那契示例,您实际上不需要执行变量的更改。但是,使用
two
函数,可以更轻松地编写关系。The formulation of the function almost is a recurrence relation. Basically, all you need to do is perform a change of variables so the argument to
two
in the recursion isn
. For example, take the following Fibonacci function:You wouldn't want to use that implementation, since it's horribly inefficient, but it makes writing the recurrence relation easy:
With the fibonacci example, you don't actually need to perform the change of variables. However, with your
two
function, it will make it simpler to write the relation.没有递归调用的行是在恒定时间内完成的,我们将其称为 c。
在每次递归调用 n 个奇数之后,下一个递归调用我们将使用 n-1 个偶数。
所以在最坏的情况下我们从 n 奇数开始 -> n-1是偶数-> (n-1)/2是奇数-> (n-1)/2-1 是偶数,依此类推...
如果例如我们从 n=19 开始,那么 19 是奇数 -> 18 是偶数 -> 9 是奇数 -> 8 是偶数 -> 4是偶数-> 2 是偶数 -> 0.
递归树的深度约为lgn,由于每层有c次操作,因此运行时间为clgn=O(lgn)。
The lines that don't have recursive calls are done in a constant time that we will call c.
After each recursive call with n odd, the next recursive call we be with n-1 even.
So in the worst case we start with n odd -> n-1 is even -> (n-1)/2 is odd -> (n-1)/2-1 is even and so on...
If for example we start with n=19 then 19 is odd -> 18 is even -> 9 is odd -> 8 is even -> 4 is even -> 2 is even -> 0.
The depth of the recursive tree is about lgn, and since on each level there are c operations then the running time is clgn=O(lgn).