Implementation of the exponentiation function. C / C++

Tell me the best algorithm for implementing the exponentiation function (pow).

Author: Nicolas Chabanovsky, 2010-10-27

7 answers

It may not be the best way, but it works!

 long int pow(long int x, unsigned int n)
 {
    if (n==0)
        return 1;
    else if (n==1)
        return x;
    else if (n % 2 == 0 )
        return pow( x * x, n/2);
    else
        return pow( x * x, n /2)*x;
 }
 5
Author: Nicolas Chabanovsky, 2010-12-15 18:10:13

Specify the question, or the previous answer will be correct. If it is necessary to calculate the real power of a number, then the formula b^x = exp(x*ln(b)). If you need to implement both the exponent and the natural logarithm functions, please decompose them by Taylor.

 4
Author: Singlet, 2010-12-20 14:28:41

Comment on all responses. What to do with overflow? It is not analyzed anywhere.

For example, the library function

double pow(double x, double y)

Sets errno to ERANGE

 4
Author: avp, 2011-05-07 20:07:07

Shortest code (:

class big{/*реализация длинной арифметики*/};
big BinPow(big a, long long n){
    big res = big(1); // тут res = 1
    while (n) n & 1 ? (res *= a, --n) : (a *= a, n >> 1);
    reutn res;
}

In general, properties are used here:
1. a^n = a^(n/2) * a^(n/2) for odd n;
2. a^n = a^(n/1) * a - for even n.

Long for pathos (:

 4
Author: outoftime, 2012-12-22 16:26:24

I would implement the same algorithm as in the first answer, but iteratively, without wasting extra time on the recursive call and O (log n) memory in the call stack, and with small optimizations. The following code only works for non-negative integers n, for other values of n, use the Taylor series expansion.

long int pow(long int x, unsigned int n)
{
    long int a = x, p = 1;
    while (n > 0)
    {
        if ((n & 1) != 0)
            p *= a;
        a *= a;
        n >>= 1;
    }
    return p;
}
 3
Author: ofitserov, 2011-01-06 19:12:49

It can be much easier:

int pwr (register int m, register int e)
{
    register int temp;
    temp = 1;

    for( ; e; e--)
        tempс= temp * m;

    return temp;
}
 1
Author: mozg, 2011-01-09 11:57:07
int pow(int a,int n)
{
    if(n==0) return 1;
    else
        if(n==1) return a;
    else
        return pow(a+a, n-1);
}
 -2
Author: Rustam1991, 2016-06-15 16:12:03