[英]How to calculate time complexity of the following algorithm
How to calculate time complexity of the following algorithm. 如何计算以下算法的时间复杂度。 I tried but I am getting confused because recursive calls. 我尝试过,但由于递归调用而感到困惑。
power (real x, positive integer n)
//comment : This algorithm returns xn, taking x and n as input
{
if n=1 then
return x;
y = power(x, |n/2|)
if n id odd then
return y*y*x //comment : returning the product of y2 and x
else
return y * y //comment : returning y2
}
can some one explain in simple steps. 可以用简单的步骤来解释一下。
To figure out the time complexity of a recursive function you need to calculate the number of recursive calls that is going to be made in terms of some input variable N
. 为了弄清递归函数的时间复杂度,您需要计算将要根据某些输入变量N
进行的递归调用的次数。
In this case, each call makes at most one recursive invocation. 在这种情况下,每个调用最多进行一个递归调用。 The number of invocations is on the order of O(log 2 N), because each invocation decreases N
in half. 调用次数约为O(log 2 N),因为每次调用都会使N
减少一半。
The rest of the body of the recursive function is O(1), because it does not depend on N
. 递归函数的其余部分为O(1),因为它不依赖于N
Therefore, your function has time complexity of O(log 2 N). 因此,您的函数的时间复杂度为O(log 2 N)。
Each call is considered a constant time operation, and how many times will it recurse is equal to how many times can you do n/2 before n = 1, which is at most log 2 ( n
) times. 每个调用都被视为固定时间操作,并且它将递归多少次等于您可以在n = 1之前执行n / 2次,这最多是log 2 ( n
)次。 Therefore the worst case running time is O(log 2 n
). 因此,最坏情况下的运行时间为O(log 2 n
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.