VOOZH about

URL: https://www.geeksforgeeks.org/dsa/modular-exponentiation-power-in-modular-arithmetic/

⇱ Modular Exponentiation (Power in Modular Arithmetic) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Modular Exponentiation (Power in Modular Arithmetic)

Last Updated : 5 Feb, 2026

Given three integers x, n, and M, compute (xn) % M (remainder when x raised to the power n is divided by M).

Examples :

Input: x = 3, n = 2, M = 4
Output: 1
Explanation: 32 % 4 = 9 % 4 = 1.

Input: x = 2, n = 6, M = 10
Output: 4
Explanation: 26 % 10 = 64 % 10 = 4.

[Naive Approach] Repeated Multiplication Method - O(n) Time and O(1) Space

We initialize the result as 1 and iterate from 1 to n, updating the result by multiplying it with x and taking the modulo by M in each step to keep the number within integer bounds.


Output
1

[Expected Approach] Modular Exponentiation Method - O(log(n)) Time and O(1) Space

The idea of binary exponentiation is to reduce the exponent by half at each step, using squaring, which lowers the time complexity from O(n) to O(log n).
-> xn = (xn/2)2 if n is even.
-> xn = x*xn-1 if n is odd.

Step by step approach:

  • Start with the result as 1.
  • Use a loop that runs while the exponent n is greater than 0.
  • If the current exponent is odd, multiply the result by the current base and apply the modulo.
  • Square the base and take the modulo to keep the value within bounds.
  • Divide the exponent by 2 (ignore the remainder).
  • Repeat the process until the exponent becomes 0.

Output
1
Comment