快速计算幂(例如2^11)
如何以更好的运行时间计算幂?
例如2^13。
我记得在某处看到它与以下计算有关:
2^13 = 2^8 * 2^4 * 2^1
但我不知道如何计算方程右侧的每个分量然后相乘他们会帮助我。
有什么想法吗?
编辑:我的意思是任何基础。您在下面提到的算法,特别是“平方求幂”如何提高运行时间/复杂性?
Possible Duplicate:
The most efficient way to implement an integer based power function pow(int, int)
How can I calculate powers with better runtime?
E.g. 2^13.
I remember seeing somewhere that it has something to do with the following calculation:
2^13 = 2^8 * 2^4 * 2^1
But I can't see how calculating each component of the right side of the equation and then multiplying them would help me.
Any ideas?
Edit: I did mean with any base. How do the algorithms you've mentioned below, in particular the "Exponentation by squaring", improve the runtime / complexity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(6)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有一个通用的算法可以实现这一点,但在具有位移位的语言中,有一种更快的方法来计算 2 的幂。您只需输入
1 << exp
(假设您的位移运算符是<<
,就像大多数支持该操作的语言一样)。我假设您正在寻找通用算法,并且只是选择了一个不幸的基础作为示例。我将用Python给出这个算法。
这基本上使得指数能够在 log2 exp 时间内计算出来。这是一种分而治之的算法。 :-) 正如其他人所说的通过平方求幂。
如果将示例插入其中,您可以看到它是如何工作的并且与您给出的方程相关:
There is a generalized algorithm for this, but in languages that have bit-shifting, there's a much faster way to compute powers of 2. You just put in
1 << exp
(assuming your bit shift operator is<<
as it is in most languages that support the operation).I assume you're looking for the generalized algorithm and just chose an unfortunate base as an example. I will give this algorithm in Python.
This basically causes exponents to be able to be calculated in log2 exp time. It's a divide and conquer algorithm. :-) As someone else said exponentiation by squaring.
If you plug your example into this, you can see how it works and is related to the equation you give: