Open In App

Modular Exponentiation in Python

Last Updated : 08 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given three numbers x, y and p, compute (x^y) % p Examples:

Input:  x = 2, y = 3, p = 5
Output: 3
Explanation: 2^3 % 5 = 8 % 5 = 3.

Input:  x = 2, y = 5, p = 13
Output: 6
Explanation: 2^5 % 13 = 32 % 13 = 6.

The problem with above solutions is, overflow may occur for large value of n or x. Therefore, power is generally evaluated under modulo of a large number. Naive multiplication is O(n) with a very low constant factor with %m. Pow function calculates in O(log n) time in python but it takes a lot of time when numbers are large enough if you first calculate the value of xy and then mod it with p to get (xy) % p evaluated. 

Python3




# Simple python code that first calls pow()
# then applies % operator.
a = 2
b = 100
p = (int)(1e9+7)
 
# pow function used with %
d = pow(a, b) % p
print (d)


Output:

976371285

Time complexity: O(log b)
The time complexity of pow(a, b) is O(log b) as it is using the binary exponentiation algorithm. The modulo operation takes constant time. So, the overall time complexity of the code is O(log b).

Auxiliary Space: O(1)
The code uses constant space for storing the integer values of a, b, and p. Hence, the auxiliary space complexity is O(1).

While computing with large numbers modulo, the (%) operator takes a lot of time, so a Fast Modular Exponentiation is used. Python has pow(x, e, m) to get the modulo calculated which takes a lot less time. [Please refer Python Docs for details] 

Python3




# Fast python code that first calls pow()
# then applies % operator
a = 2
b = 100
p = (int)(1e9+7)
 
# Using direct fast method to compute
# (a ^ b) % p.
d = pow(a, b, p)
print (d)


Output:

976371285

The fast modular exponentiation algorithm has been explained more briefly in link


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads