Python program for Modular Exponentiation



What is Modular Exponentiation?

To calculate Modular exponentiation, we need to raise a base to an exponent and then calculate the modulus of the result. This includes 3 integers: base, exponent, and modulo. Following is the syntax of the modular exponentiation in Python -

(base**exponent) % modulo

For instance, consider (2^5) % 5, which indicates 2 raised to the power of 5, which results in 32; When the modulo operation is performed, it returns the remainder, i.e., 32 % 5 is 3.

Modular Exponentiation using Recursive Function

A function that calls itself is known as a recursive function. Following is the algorithm to find the modular exponentiation -

  • Step 1: If the exponent is 0, then return 1.
  • Step 2: If the exponent is 1, then perform a modular operation.
  • Step 3: Call the function recursively by passing half of the exponent. Based on whether the exponent is even or odd, calculate the result using the half_power result.

Example

In the following example, the modular exponentiation is performed without using a function -

def mod_exp(base, exponent, mod):
   if exponent == 0:
      return 1

   if exponent == 1:
      return base % mod

   half_power = mod_exp(base, exponent // 2, mod)

   if exponent % 2 == 0:
      return (half_power * half_power) % mod
    
   else:
      return (base * half_power * half_power) % mod

base = 2  
exponent = 3
mod = 6
result = mod_exp(base, exponent, mod)
print("The recursive modulo exponential of", "(", base, "power", exponent, ")", "%", mod, "is:", result)

Following is the output of the above code -

The recursive modulo exponential of ( 2 power 3 ) % 6 is: 2

Using pow() Function

In Python, the pow() function is used to perform modular exponentiation. It calculates in O(log n) time, and it takes more time when large numbers are passed as arguments. It will first evaluate baseexponent, and then the mod operation is performed.

base = 2 #base value
exponent = 5 #exponent value
mod = 5 
result=pow(2,5,5) # exponential modulo operator
print("The modulo exponential of ","(",2,"power",5,")","%",5,"is :",result)

Following is the output of the above code -

The modulo exponential of  ( 2 power 5 ) % 5 is : 2
Updated on: 2025-06-23T17:26:07+05:30

764 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements