# Modular Exponentiation in Python

• Difficulty Level : Medium
• Last Updated : 23 Nov, 2020

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.
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

 `# 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
```

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]

 `# 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

My Personal Notes arrow_drop_up