Integer power of a value
1. Question
Implement the double Power (double base, int exponent) function to calculate the exponent Power of the base. Do not use library functions, and do not need to consider large numbers.
2. Analysis
First, determine the range of base and exponent, because exponent is greater than 0, there will be no one and restrictions. This is the integer power of the value. Therefore, we need to consider the case where it is smaller than 0.
(1) data input error when base = 0.0 and exponent <0.
(2) base! = 0.0 and exponent> 0.
(3) base! = 0.0 and exponent <0, base is multiplied (-exponent) times, and the final result is counted down.
3. Implementation
3.1 direct Multiplication
double Power(double base, int expoent){ if (base > -0.0000001 && base < 0.0000001 && expoent < 0) { cout << "invalid input" << endl; return 0.0; } if (expoent > 0) { return Multiplicative(base, expoent); } else { expoent *= -1; return 1.0/Multiplicative(base, expoent); }}double Multiplicative(double base, int exponet){ double result = 1.0; for (int i = 0; i < exponet; ++i) { result *= base; } return result;}
3.2 recursive decomposition
(1) When the power index is an even number, x 32 = X 16 * X 16
(2) When the power index is an odd number, x 31 = X 15 * X 15 * X
Therefore, Multiplicative in 3.1 can be implemented using the following recursive method:
double MultiplicativeImpRecurtive(double base, int exponet){ if (0 == exponet) { return 1.0; } if (1 == exponet) { return base; } double result = MultiplicativeImpRecurtive(base, exponet >> 1); result *= result; if (exponet & 0x1) { result *= base; } return result;}
3.3 non-recursive decomposition
double MultiplicativeImpIterative(double base, int exponet){ double result = 1.0, x = base; while (exponet > 0) { if (exponet & 0x1) { result *= x; } x *= x; exponet >>= 1; } return result;}