简体   繁体   English

递归算法的时间复杂度

[英]time complexity of the recursive algorithm

Can someone please explain to me how to calculate the complexity of the following recursive code: 有人可以向我解释如何计算以下递归代码的复杂性:

long bigmod(long b, long p, long m) {
    if (p == 0)
        return 1;
    else
    if (p % 2 == 0)
        return square(bigmod(b, p / 2, m)) % m;
    else    
        return ((b % m) * bigmod(b, p - 1, m)) % m;
}

This is O(log(p)) because you are dividing by 2 every time or subtracting one then dividing by two, so the worst case would really take O(2 * log(p)) - one for the division and one for the subtraction of one. 这是O(log(p)),因为你每次除以2或减去除以2然后除以2,所以最坏的情况确实需要O(2 * log(p)) - 一个用于除法,一个用于除法减去一个。

Note that in this example the worst case and average case should be the same complexity. 请注意,在此示例中,最坏情况和平均情况应该是相同的复杂性。

If you want to be more formal about it then you can write a recurrence relation and use the Master theorem to solve it. 如果你想对它更正式,那么你可以写一个递归关系并使用Master定理来解决它。 http://en.wikipedia.org/wiki/Master_theorem http://en.wikipedia.org/wiki/Master_theorem

它是o(log(N))base 2,因为除以2

It runs in O(log n) 它在O(log n)

There are no expensive operations (by that i more expensive than squaring or modding. no looping, etc) inside the function, so we can pretty much just count the function calls. 在函数内部没有昂贵的操作(因为我比平方或修改更昂贵。没有循环等),所以我们几乎可以只计算函数调用。

Best case is a power of two, we will need exactly log(n) calls. 最好的情况是2的幂,我们将需要准确的log(n)调用。

Worst case we get an odd number on every other call. 最糟糕的情况是,我们在每次其他通话中都会得到一个奇数。 This can do no more than double our calls. 这只能使我们的电话加倍。 Multiplication by a constant factor, no worse asymptotically. 乘以常数因子,不会渐近变差。 2*f(x) is still O(f(x))

O(logn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM