Modular Exponentiation in Python

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

976371285

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]

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output:

976371285

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



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.