Ishaan28malik / Hacktoberfest-2023

Make this Hacktoberfest a learning period and contribute to Great Open Source Projects.
MIT License
550 stars 1.71k forks source link

Exponentiation_By_Squaring #1976

Open Devika-H opened 10 months ago

Devika-H commented 10 months ago

In this program:

  1. The power function takes a base x (a double) and an exponent n (an integer) as parameters.

  2. 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.

  3. 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.

  4. In the main function, the user is prompted to enter the base and exponent values.

  5. 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.