The power function takes a base x (a double) and an exponent n (an integer) as parameters.
It first handles the special cases where the exponent is 0 or negative. If n is 0, it returns 1.0 because any number raised to the power of 0 is 1. If n is negative, it calculates the reciprocal of x and makes n positive.
It then uses a while loop to iteratively calculate the result. It uses the "exponentiation by squaring" algorithm, which is more efficient than the naive iterative method. It reduces the exponent by half in each iteration and squares the base accordingly, multiplying the result only when the current bit of the exponent is 1.
In the main function, the user is prompted to enter the base and exponent values.
The power function is called with the provided values, and the result is printed.
This program allows you to calculate the power of a number efficiently for both positive and negative exponents.
In this program:
The
power
function takes a basex
(a double) and an exponentn
(an integer) as parameters.It first handles the special cases where the exponent is 0 or negative. If
n
is 0, it returns 1.0 because any number raised to the power of 0 is 1. Ifn
is negative, it calculates the reciprocal ofx
and makesn
positive.It then uses a while loop to iteratively calculate the result. It uses the "exponentiation by squaring" algorithm, which is more efficient than the naive iterative method. It reduces the exponent by half in each iteration and squares the base accordingly, multiplying the result only when the current bit of the exponent is 1.
In the
main
function, the user is prompted to enter the base and exponent values.The
power
function is called with the provided values, and the result is printed.This program allows you to calculate the power of a number efficiently for both positive and negative exponents.