(Translated by https://www.hiragana.jp/)
Modular Exponentiation (Power in Modular Arithmetic) - GeeksforGeeks
Open In App

Modular Exponentiation (Power in Modular Arithmetic)

Last Updated : 14 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
#include<iostream>
using namespace std;

int powMod(int x, int n, int M) {
    
    // Initialize result as 1 (since anything power 0 is 1)
    int res = 1;

    // n times to multiply x with itself
    for(int i = 1; i <= n; i++) {
                
        // Multiplying res with x 
        // and taking modulo to avoid overflow
        res = (res * x) % M;
    }

    return res;
}

int main() {
    
    int x = 3, n = 2, M = 4;
    cout << powMod(x, n, M) << endl;
    return 0;
}
Java Python C# JavaScript

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.
C++
#include<iostream>
using namespace std;

int powMod(int x, int n, int M) {
    int res = 1;

    // Loop until exponent becomes 0
    while(n >= 1) {
        
        // n is odd, multiply result by current x and take modulo
        if(n & 1) {
            res = (res * x) % M;
            
            // Reduce exponent by 1 to make it even
            n--;  
        }
        
        // n is even, square the base and halve the exponent
        else {
            x = (x * x) % M;
            n /= 2;
        }
    }
    return res;
}

int main() {
    int x = 3, n = 2, M = 4;
    cout << powMod(x, n, M) << endl;
}
Java Python C# JavaScript

Output
1

Similar Reads