Prompt the best algorithm for implementing the exponentiation function (pow).
- “best” is rather vague: the fastest for small (fixed integers) on the selected architecture or the fastest for large integers (for example, which are used in cryptography) or the most accurate for float, double arguments in a certain range or algorithm that uses the least number of multiplications (theoretically interesting) or the simplest (for a programmer) and tested algorithm: call std :: pow (), and so on. - jfs
7 answers
Maybe this is not 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; }
Clarify 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 it is necessary to realize both the functions of the exponent and the natural logarithm, please decompose them according to Taylor .
- Taylor is one of the most inefficient ways ... Professionals use orthogonal polynomials (usually Chebyshev) - Barmaley
Comment to all the answers. What to do with overflow? Nowhere is it analyzed.
For example 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 spending too much time on the recursive call and O (log n) memory in the call stack, and with small optimizations. The following code works only for nonnegative integer n, for other values of n, use Taylor 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 simpler:
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); }
- This multiplication - Error