简体   繁体   English

这个用于计算^ n的算法如何被重写以在O(log n)时间内运行?

[英]How did this algorithm for computing a^n get rewritten to run in O(log n) time?

Suppose you want to compute a n . 假设您要计算n A simple algorithm would multiply a, n times, as follows: 一个简单的算法将乘以a,n次,如下所示:

result = 1;
for(int i =1; i <= n; i++)
    result *= a; 

The algorithm takes O(n) time. 该算法需要O(n)时间。 Without loss of generality, assume n=2^k 不失一般性,假设n = 2 ^ k

You can improve the algorithm using the following scheme: 您可以使用以下方案改进算法:

 result = a;
 for (int i = 1; i <= k; i++)
     result = result * result; 

The algorithm takes O(log n) time. 该算法需要O(log n)时间。 For an arbitrary n, you can revise the algorithm and prove that the complexity is still O(logn) 对于任意n,您可以修改算法并证明复杂性仍为O(logn)

So confused, so how is n=2 k , and why is k only shown in the second example? 如此困惑,那么如何n = 2 k ,为什么k只在第二个例子中显示? Don't understand how this transformed into a O(logn) time complexity... 不明白这是如何转化为O(logn)时间复杂度的......

The second algorithm doesn't work in the general case; 第二种算法在一般情况下不起作用; it only works if there is some k such that you can write n = 2 k . 只有当某些k可以写n = 2 k时它才有效。 If there is ak where you can do this, then by taking the logs of both sides of the equality you get that log 2 n = k. 如果有ak你可以做到这一点,那么通过获取相等两边的日志,你得到那个log 2 n = k。 Therefore: 因此:

  • The loop, which counts up to k, runs O(log n) times. 循环计数到k,运行O(log n)次。
  • Therefore, the loop runs in time O(log n). 因此,循环在时间O(log n)中运行。

If you want to get rid of the mysterious k, you could write 如果你想摆脱神秘的k,你可以写

int result = a;
for (int i = 0; i < log2(n); i++) {
    result = result * result;
}

This more clearly runs in O(log n) time, since the loop runs log 2 n times and does O(1) work on each iteration. 这更明显地在O(log n)时间内运行,因为循环运行log 2 n次并且O(1)在每次迭代时都起作用。

I don't think it's fair to say "without loss of generality" that n is a perfect power of two, since not all numbers are! 我不认为说“不失一般性”,n是2的完美力量是公平的,因为不是所有数字都是! The above code will only work if n is a power of two. 只有当n是2的幂时,上述代码才有效。 You can generalize it to non-powers-of-two by using the repeated squaring algorithm , which has O(log n) complexity but works for any power. 您可以使用重复的平方算法将其推广到非幂次幂,该算法具有O(log n)复杂度但适用于任何功率。

Hope this helps! 希望这可以帮助!

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

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