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
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Visualizing O(n) using Python
- abs() in Python
- gcd() in Python
- bin() in Python
- Python | a += b is not always a = a + b
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.