Modular Exponentiation in Python
Given three numbers x, y and p, compute (x^y) % p
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.
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]
The fast modular exponentiation algorithm has been explained more briefly in link