Open In App

Modular Exponentiation in Python

Last Updated : 08 Mar, 2023
Like Article

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. 


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



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] 


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



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

Similar Reads

Python | Exponentiation by K in list
While working with the python lists, we can come across a situation in which we require to exponent constant for each element in the list. We possibly need to iterate an exponent constant to each element but that would increase the line of code. Let’s discuss certain shorthands to perform this task. Method #1: Using List Comprehension List comprehe
5 min read
Python - Cross list exponentiation
Sometimes we come across situations in which we require to apply a particular function to each element of two lists at similar indices. These are quite similar and come up as an application for certain utilities. Let’s discuss certain ways in which the exponentiation, i.e remainder of two lists can be performed. Method #1: Using zip() + list compre
7 min read
Python | Size and element exponentiation of list
Sometimes, while working with Python lists, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat the contents of the list and while doing that, each time new list must be exponentiation of the original list. This incremental expansion has applications in many domains. Let’s discuss a way in which t
4 min read
Find the value of P and modular inverse of Q modulo 998244353
Given two integer P and Q, the task is to find the value of P and modular inverse of Q modulo 998244353. That is [Tex]P * Q^{-1} \% 998244353 [/Tex] Note: P and Q are co-prime integersExamples: Input: P = 1, Q = 4Output: 748683265Explanation:Refer below for the explanation of the example. Input: P = 1, Q = 16Output: 935854081 Approach: The key obse
5 min read
Using Chinese Remainder Theorem to Combine Modular equations
Given N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing the set of values of each prime. mi Output an int
12 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Practice Tags :