
Kevin S. answered 09/28/23
Tutor
5.0
(379)
Experienced Computer Science Tutor: 20 Years Experience
/**
* @brief Calculates x raised to the power n.
*
* @param x The base.
* @param n The exponent.
* @return The result of x raised to the power n.
*/
double myPow(double x, int n) {
// Base cases: n = 0 or n = 1if (n == 0) return 1.0;
if (n == 1) return x;
double result = 1.0;
long long N = n; // Using long long to safely handle edge case of n = -2^31
// If n is negative, take the reciprocal of x and negate nif (N < 0) {
x = 1 / x;
N = -N;
}
// Current product, initialized to xdouble current_product = x;
// Exponentiation by squaringfor (; N; N >>= 1) {
// If the last bit of N is set (N is odd), multiply the result by the current productif (N & 1) {
result *= current_product;
}
// Square the current product for the next iteration
current_product *= current_product;
}
return result;
}