Exponentiation
Understand the efficiency and effectiveness of the exponentiation algorithm.
We'll cover the following...
Naïve method
Given a number and a positive integer , suppose we want to compute . The standard naïve method is a simple for
loop that performs multiplications by :
Algorithm
Implementation
def slow_power(a, n):x = afor i in range(2, n + 1):x = x * areturn xprint("Answer is :", slow_power(16, 2))
Explanation
-
Lines 1–5: We compute the value of a positive integer raised to the power of another positive integer
n
using a simplefor
loop that performsn-1
multiplications. The function iteratively multipliesx
byn-1
times. Finally, the function returns the value ofx
. However, this method has a time complexity of , which can be very slow for large values ofn
. -
Line 8: We print the result on the console.
Fast exponentiation algorithm
This iterative algorithm requires multiplications. The input parameter could be an integer, a rational, or a floating point number. In fact, it doesn’t need to be a number at all as long as it’s something that we know how to multiply. For example, the same algorithm can be used to compute powers modulo some finite number (an operation commonly used in cryptography algorithms) or to compute powers of matrices (an operation used to evaluate recurrences and to compute shortest paths in graphs). Because we don’t know what kind of object we’re multiplying, we can’t know how much time a single multiplication requires, so we’re forced to analyze the running time in terms of the number of multiplications.
There is a much faster divide-and-conquer method, originally proposed by the Indian prosodist in the 2nd century BCE, which uses the following simple recursive formula:
...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy