Implementation of the exponentiation function. C / C++
Tell me the best algorithm for implementing the exponentiation function (pow).
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;
}
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.
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
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 (:
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;
}
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;
}
int pow(int a,int n)
{
if(n==0) return 1;
else
if(n==1) return a;
else
return pow(a+a, n-1);
}