The most efficient way to implement an integer based power function pow(int, int) The most efficient way to implement an integer based power function pow(int, int) c c

The most efficient way to implement an integer based power function pow(int, int)


Exponentiation by squaring.

int ipow(int base, int exp){    int result = 1;    for (;;)    {        if (exp & 1)            result *= base;        exp >>= 1;        if (!exp)            break;        base *= base;    }    return result;}

This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.


Note that exponentiation by squaring is not the most optimal method. It is probably the best you can do as a general method that works for all exponent values, but for a specific exponent value there might be a better sequence that needs fewer multiplications.

For instance, if you want to compute x^15, the method of exponentiation by squaring will give you:

x^15 = (x^7)*(x^7)*x x^7 = (x^3)*(x^3)*x x^3 = x*x*x

This is a total of 6 multiplications.

It turns out this can be done using "just" 5 multiplications via addition-chain exponentiation.

n*n = n^2n^2*n = n^3n^3*n^3 = n^6n^6*n^6 = n^12n^12*n^3 = n^15

There are no efficient algorithms to find this optimal sequence of multiplications. From Wikipedia:

The problem of finding the shortest addition chain cannot be solved by dynamic programming, because it does not satisfy the assumption of optimal substructure. That is, it is not sufficient to decompose the power into smaller powers, each of which is computed minimally, since the addition chains for the smaller powers may be related (to share computations). For example, in the shortest addition chain for a¹⁵ above, the subproblem for a⁶ must be computed as (a³)² since a³ is re-used (as opposed to, say, a⁶ = a²(a²)², which also requires three multiplies).


If you need to raise 2 to a power. The fastest way to do so is to bit shift by the power.

2 ** 3 == 1 << 3 == 82 ** 30 == 1 << 30 == 1073741824 (A Gigabyte)