Fast Exponentiation in Python
Last Updated :
26 Apr, 2025
We are going to learn about how it can be optimized or make fast computations or how to use exponents in Python to the power of numbers as compared to the traditional method using Python.
What is Exponentiation?
It is a mathematical operation in which we compute the expression ab by repeating the multiplication of a by b several times. Where ‘a’ is known as base and ‘b’ is known as power. Let’s take an example of exponentiation as explained below:
Example:
Let’s assume we have to calculate the 54. So 54 can be expanded by multiplying the 5 itself 4 times as number mentioned in the superscript(or power) as explained below:-
Base = 5, Power = 4
54 = 5*5*5*5 = 625
Fast Exponentiation in Python
Fast Exponentiation is the optimization of the traditional methods of computing the powers. Optimization can be done by reducing extra iteration from the for-loop conditional statement. Let’s understand the implementation of using Exponents in Python. We will optimize by two methods:
- Exponents using the pow() function
- Without using the pow() function.
- By using divide and conquer method
- Exponents in Python using Math.pow()
- Exponents in Python using the list
- Exponents in Python with for loop
Fast Exponentiation using pow() function
Fast exponentiation refers to an efficient algorithm for calculating the power of a number. The pow() function in Python is often used for this purpose.
Example: Here, we are computing the half power for the optimization method, e.g. if we have to calculate 54 then we calculate 52. If the power is odd then one value gets multiple with the remaining result to get the desired result.
Python3
def optimize(val, power):
result = pow(val, power//2)
result = result * result
if power % 2 != 0:
result = result * val
return result
cal = optimize(2, 5)
print(cal)
|
Output:
32
Time Complexity: O(log n) Auxiliary Space: O(1)
Fast Exponentiation without using pow() function
In this, we are optimizing without using the power function. If the power is positive it means we have to multiply it directly, and if the power is negative we will have to multiply the 1/val repeatedly. Here we have reduced the number of iterations from the exponentiation to optimize the code for larger numbers.
Example : In this example the below code`optimize` function efficiently computes the power of a value using a divide-and-conquer approach. It handles positive and negative exponents, and the example `optimize(2, -2)` demonstrates this optimization. The result is then printed.
Python3
def optimize(val, power):
result = 1
if val == 0:
return 0
if power > 0:
for i in range(1, (power//2)+1):
result = result * val
result = result * result
if power % 2 != 0:
result = result * val
elif power < 0:
for i in range(1, ((-power//2) + 1)):
result = result * 1/val
result = result * result
if power % 2 != 0:
result = result * 1/val
else:
pass
return result
cal = optimize(2, -2)
print(cal)
|
Output:
0.25
Time Complexity: O(power/2) Auxiliary Space: O(1)
Fast Exponentiation using the divide and conquer method
In this approach, we will be dividing the exponent into the subproblem and will multiply the number by calling the function recursively.
Example : In this example the `power` function efficiently calculates x raised to the power y in O(logn) time using a recursive divide-and-conquer approach. The provided example demonstrates its use by calculating and printing results for `2^5` and `3^6`.
Python3
def power(x, y):
temp = 0
if(y == 0):
return 1
temp = power(x, int(y / 2))
if y % 2 == 0:
return temp * temp
else:
return x * temp * temp
result1 = power(2, 5)
print(result1)
result2 = power(3, 6)
print(result2)
|
Output:
32
729
Time Complexity: O(log n)
Auxiliary Space: O(log n)
Fast Exponentiation in Python using Math.pow()
In Python, `math.pow()` computes the power of a given number with two arguments: base and exponent. It returns the result as a floating-point number, providing an efficient way to perform exponentiation in mathematical calculations.
Example : In this example, math.pow(2, 3) calculates and returns the result of 2 raised to the power 3, which is 8.0. Note that the result is always a floating-point number, even if the base and exponent are intege
Python3
import math
result = math.pow(2, 3)
print(result)
|
Output :
8.0
Fast Exponentiation in Python using List
Fast exponentiation using a list or array in Python typically refers to an optimization technique to efficiently calculate exponentiation, particularly for large exponents. This often involves precomputing powers of the base and then using these precomputed values to construct the final result.
Example : In this example the code uses a fast exponentiation technique to compute 2^10 efficiently, precomputing powers of 2 and leveraging bitwise operations. The output, 1024, is obtained when calling the function with `fast_exponentiate(2, 10)`.
Python3
def fast_exponentiate(base, exponent):
powers = [1]
for _ in range(exponent.bit_length() - 1):
powers.append(powers[-1] * powers[-1])
result = 1
mask = 1 << (exponent.bit_length() - 1)
for power in powers[::-1]:
result *= power if (exponent & mask) else 1
mask >>= 1
return result
result = fast_exponentiate(2, 10)
print(result)
|
Output :
1024
Fast Exponentiation in Python With For Loop
Fast exponentiation with a for loop is an algorithm that efficiently calculates the power of a number using iteration. The key idea is to express the exponent in binary form and use a loop to compute the result by considering the binary bits.
Example : In this example in the below code `fast_exponentiation` function efficiently computes the power of a number using binary exponentiation, reducing unnecessary multiplications. The example demonstrates calculations for 2^5 and 3^6.
Python3
def fast_exponentiation(base, exponent):
result = 1
while exponent > 0:
if exponent % 2 == 1:
result *= base
base *= base
exponent //= 2
return result
result1 = fast_exponentiation(2, 5)
print(result1)
result2 = fast_exponentiation(3, 6)
print(result2)
|
Output :
32
729
Similar Reads
CSES Solutions - Exponentiation
Your task is to efficiently calculate values a^b modulo 109+7. Note that in this task we assume that 00=1. Examples: Input: N = 3, queries[][] = {{3, 4}, {2, 8}, {123, 123}}Output: 81256921450052Explanation: The first query is (3 ^ 4) % (109 + 7) = (3 * 3 * 3 * 3) % (109 + 7) = 81The second query is
7 min read
CSES Solutions - Exponentiation II
Your task is to efficiently calculate values a^(b^c) modulo 109+7. Note that in this task we assume that 00 = 1. Examples: Input: N = 2, queries[][] = {{3, 7, 1}, {2, 3, 2}}Output: 2187512Explanation: 3 ^ (7 ^ 1) mod 109+7 = 3 ^ 7 = 21872 ^ (3 ^ 2) mod 109+7 = 2 ^ 9 = 512 Input: N = 3, queries[][] =
6 min read
What is 125 in the exponential form?
Answer: Exponents and powers are a method to express repeated multiplication of the same number. For eg- 6 Ã 6 Ã 6 Ã 6 can be written as 64 where 6 is the base and 4 is the exponent. It is most commonly used to express the powers of 10 to write a very large number conveniently. For eg - 100000 can b
3 min read
math.pow() in Python
In Python, math.pow() is a function that helps you calculate the power of a number. It takes two numbers as input: the base and the exponent. It returns the base raised to the power of the exponent. In simple terms, if you want to find "x raised to the power y", you can use math.pow(x, y). Example:
3 min read
Karatsuba Algorithm in Python
Karatsuba Algorithm is a fast multiplication algorithm that efficiently multiplies large numbers by recursively breaking them down into smaller parts. Examples: Input: A = 5678 B = 1234Output: 7006652 Input: A = 1456 B = 6533Output: 9512048 Using the Naive approach, we can multiply two numeric strin
4 min read
Practice Questions on Exponents and Powers
Exponents and powers play a crucial role in mathematics, allowing us to express large numbers efficiently and solve problems involving repeated multiplication. Exponential numbers refer to numbers expressed using an exponent or power. They involve a base number raised to an exponent. The general for
6 min read
How to Minimize Python Script Execution Time?
Minimizing Python script execution time is essential for improving performance, especially in production environments, competitive programming (CP) or data structures and algorithms (DSA). Faster execution ensures better user experience in apps and helps us perform well in coding challenges. In this
3 min read
Display scientific notation as float in Python
In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with "{:e}" to format the number to
2 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
2 min read
Divide all Elements of a List by a Number in Python
The task of dividing all elements of a list by a number in Python involves iterating over the list and applying the division operation to each element. For example, given a list a = [14, 8, 0, 12, 981, 21, -99] and a divisor d = 7, the result after dividing each element by 7 will be [2, 1, 0, 1, 140
3 min read