Calculate Power of a Number
Explore how to calculate a number raised to an integer power efficiently by applying a divide and conquer algorithm. Learn to break down the problem recursively, handling even and odd powers to reduce the number of multiplications. Understand the time and space complexities involved to optimize your coding solutions in mathematical problem solving.
We'll cover the following...
Statement
Given a double number, , and an integer, , implement a function to calculate raised to the power .
Example:
Given input | Power |
power(0, 0) | 1.000 |
power(2, 5) | 32.000 |
power(3, 4) | 81.000 |
power(1.5, 3) | 3.375 |
power(2, -2) | 0.250 |
Sample input
pow(2,5)
Expected output
32
Try it yourself
Solution
A simple algorithm for this problem is to multiply x with itself by n times:
We can reduce the number of multiplications, in a classic divide and conquer approach, exploiting this property of exponents: