Power Function
excerpt: This covers the iterative and recursive implementation of power function. tags: product-accumulator modulo-operator reduction-of-input-value odd even
Implement integer exponentiation. That is, implement the power(x, y) function, where x and y are integers and returns x^y.
Naive Implementation
The implementation for iterative power function:
|
|
The key insight to write the code for exponentiation is that exponentiation is repeated multiplication.
Building Block
- Product Accumulator
The recursive implementation of power function:
|
|
Faster Implementation
Can we do this faster than the naive method of repeated multiplication? Yes, we can the improve the performance. We can reduce the number of multiplications in the recursive approach:
𝑥^18 = 𝑥^9∗𝑥^9
𝑥^9 = 𝑥^4∗𝑥^4∗𝑥 𝑥^4 = 𝑥^2∗𝑥^2
|
|
The iterative improved version is shown below:
|
|