快速计算幂(例如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:
使用按位移位。前任。 1<<; 11 返回 2^11。
Use bitwise shifting. Ex. 1 << 11 returns 2^11.
2 的幂是最简单的。在二进制中,2^13 是一个 1 后跟 13 个零。
您可以使用位移位,这是许多语言中的内置运算符。
Powers of two are the easy ones. In binary 2^13 is a one followed by 13 zeros.
You'd use bit shifting, which is a built in operator in many languages.
您可以使用通过平方求幂。这也称为“平方乘”,也适用于基数 != 2。
You can use exponentiation by squaring. This is also known as "square-and-multiply" and works for bases != 2, too.
如果您不将自己限制为 2 的幂,则:
k^2n = (k^n)^2
If you're not limiting yourself to powers of two, then:
k^2n = (k^n)^2
我所知道的最快的免费算法是
Phillip S. Pang, Ph.D
并且可以在这里找到源代码。它使用表驱动分解,可以使exp()函数比Pentium(R)处理器的原生exp()快2-10倍。
The fastest free algorithm I know of is by
Phillip S. Pang, Ph.D
and can the source code can be found here.It uses table-driven decomposition, by which it is possible to make exp() function, which is 2-10 times faster, then native exp() of Pentium(R) processor.