Calculating powers (e.g. 2^11) quickly [duplicate]

♀尐吖头ヾ 提交于 2019-12-05 03:09:42
Omnifarious

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.

def intpow(base, exp):
   if exp == 0:
      return 1
   elif exp == 1:
      return base
   elif (exp & 1) != 0:
       return base * intpow(base * base, exp // 2)
   else:
       return intpow(base * base, exp // 2)

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:

intpow(2, 13)
2 * intpow(4, 6)
2 * intpow(16, 3)
2 * 16 * intpow(256, 1)
2 * 16 * 256 == 2^1 * 2^4 * 2^8

Use bitwise shifting. Ex. 1 << 11 returns 2^11.

You can use exponentiation by squaring. This is also known as "square-and-multiply" and works for bases != 2, too.

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.

If you're not limiting yourself to powers of two, then:

k^2n = (k^n)^2

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!