The Wayback Machine - https://web.archive.org/web/20240714185139/https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/
Open In App

Modular Exponentiation (Power in Modular Arithmetic)

Last Updated : 24 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given three numbers x, y and p, compute (xy) % 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.

We have discussed recursive and iterative solutions for power.

Below is discussed iterative solution. 

C++14




/* Iterative Function to calculate (x^y)%p in O(log y) */
#include <iostream>
using namespace std;
 
int power(int x, int y, int p)
{
 
    // Initialize answer
    int res = 1;
 
    // Check till the number becomes zero
    while (y > 0) {
 
        // If y is odd, multiply x with result
        if (y % 2 == 1)
            res = (res * x);
 
        // y = y/2
        y = y >> 1;
 
        // Change x to x^2
        x = (x * x);
    }
    return res % p;
}
 
int main()
{
    int x = 2;
    int y = 5;
    int p = 13;
    cout << "Power is " << power(x, y, p);
    return 0;
}
 
// This code is contributed by yaswanth0412


Java




/* Iterative Function to calculate (x^y)%p in O(log y) */
class GFG {
    static int power(int x, int y, int p)
    {
        int res = 1; // Initialize result
 
        while (y > 0) {
 
            // If y is odd, multiply x with result
            if ((y & 1) != 0)
                res = res * x;
 
            // y must be even now
            y = y >> 1; // y = y/2
            x = x * x; // Change x to x^2
        }
        return res % p;
    }
 
    public static void main(String[] args)
    {
        int x = 2;
        int y = 5;
        int p = 13;
 
        int mod = power(x, y, p);
        System.out.print("Power is " + mod);
    }
}
 
// This code is contributed by Dharanendra L V.


Python3




# Iterative Function to calculate (x^y)%p in O(log y)
def power(x, y, p):
 
    # Initialize result
    res = 1
 
    while (y > 0):
 
        # If y is odd, multiply x with result
        if ((y & 1) != 0):
            res = res * x
 
        # y must be even now
        y = y >> 1  # y = y/2
        x = x * x  # Change x to x^2
 
    return res % p
 
  # Driver Code
 
 
x = 2
y = 5
p = 13
print("Power is ", power(x, y, p))
# This code is contributed by Khushboogoyal499


Javascript




<script>
/* Iterative Function to calculate (x^y) % p in O(log y) */
function power(x, y, p)
{
    let res = 1;     // Initialize result
 
    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = res*x;
 
        // y must be even now
        y = y>>1; // y = y/2
        x = x*x; // Change x to x^2
    }
    return res % p;
}
 
// Driver Code
let x = 2;
let y = 5;
let p = 13;
document.write("Power is " + power(x, y, p));
 
// This code is contributed by _saurabh_jaiswal
</script>


C#




/* Iterative Function to calculate (x^y)%p in O(log y) */
using System;
class GFG {
    static int power(int x, int y, int p)
    {
        int res = 1; // Initialize result
 
        while (y > 0) {
            // If y is odd, multiply x with result
            if ((y & 1) != 0)
                res = res * x;
 
            // y must be even now
            y = y >> 1; // y = y/2
            x = x * x; // Change x to x^2
        }
        return res % p;
    }
 
    // Driver Code
    static public void Main()
    {
        int x = 2;
        int y = 5;
        int p = 13;
        Console.Write("Power is " + power(x, y, p));
    }
}
 
// This code is contributed by Dharanendra L V.


Output

Power is 6

Time Complexity: O(log2y), where y represents the value of the given input.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
 

Efficient Approach:

The problem with the above solutions is, overflow may occur for large values of n or x. Therefore, power is generally evaluated under the modulo of a large number.

Below is the fundamental modular property that is used for efficiently computing power under modular arithmetic. 

(ab) mod p = ( (a mod p) (b mod p) ) mod p 

For example a = 50,  b = 100, p = 13
50  mod 13  = 11
100 mod 13  = 9

(50 * 100) mod 13 = ( (50 mod 13) * (100 mod 13) ) mod 13 
or (5000) mod 13 = ( 11 * 9 ) mod 13
or 8 = 8

Below is the implementation based on the above property.  

C++14




// Iterative C++ program to compute modular power
#include <iostream>
using namespace std;
 
/* Iterative Function to calculate (x^y)%p in O(log y) */
int power(long long x, unsigned int y, int p)
{
    int res = 1;     // Initialize result
 
    x = x % p; // Update x if it is more than or
                // equal to p
  
    if (x == 0) return 0; // In case x is divisible by p;
 
    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res*x) % p;
 
        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}
 
// Driver code
int main()
{
    int x = 2;
    int y = 5;
    int p = 13;
    cout << "Power is " << power(x, y, p);
    return 0;
}
 
// This code is contributed by shubhamsingh10


Java




// Iterative Java program to compute modular power
import java.io.*;
class GFG
{
 
  /* Iterative Function to calculate (x^y) in O(log y) */
  static int power(int x, int y, int p)
  {
    int res = 1; // Initialize result
 
    x = x % p; // Update x if it is more than or
    // equal to p
 
    if (x == 0)
      return 0; // In case x is divisible by p;
 
    while (y > 0)
    {
 
      // If y is odd, multiply x with result
      if ((y & 1) != 0)
        res = (res * x) % p;
 
      // y must be even now
      y = y >> 1; // y = y/2
      x = (x * x) % p;
    }
    return res;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int x = 2;
    int y = 5;
    int p = 13;
    System.out.print("Power is " + power(x, y, p));
  }
}
 
// This code is contributed by Dharanendra L V.


Python3




# Iterative Python3 program
# to compute modular power
 
# Iterative Function to calculate
# (x^y)%p in O(log y)
def power(x, y, p) :
    res = 1     # Initialize result
 
    # Update x if it is more
    # than or equal to p
    x = x % p
     
    if (x == 0) :
        return 0
 
    while (y > 0) :
         
        # If y is odd, multiply
        # x with result
        if ((y & 1) == 1) :
            res = (res * x) % p
 
        # y must be even now
        y = y >> 1      # y = y/2
        x = (x * x) % p
         
    return res
     
 
# Driver Code
 
x = 2; y = 5; p = 13
print("Power is ", power(x, y, p))
 
 
# This code is contributed by Nikita Tiwari.


C#




using System;
public class GFG
{
 
  /* Iterative Function to calculate (x^y) in O(log y) */
  static int power(int x, int y, int p)
  {
    int res = 1; // Initialize result
 
    x = x % p; // Update x if it is more than or
    // equal to p
 
    if (x == 0)
      return 0; // In case x is divisible by p;
 
    while (y > 0)
    {
 
      // If y is odd, multiply x with result
      if ((y & 1) != 0)
        res = (res * x) % p;
 
      // y must be even now
      y = y >> 1; // y = y/2
      x = (x * x) % p;
    }
    return res;
  }
 
  // Driver Code
  static public void Main ()
  {
    int x = 2;
    int y = 5;
    int p = 13;
    Console.Write("Power is " + power(x, y, p));
  }
}
 
// This code is contributed by Dharanendra L V.


PHP




<?php
// Iterative PHP program to
// compute modular power
 
// Iterative Function to
// calculate (x^y)%p in O(log y)
function power($x, $y, $p)
{
    // Initialize result
    $res = 1;
 
    // Update x if it is more
    // than or equal to p
    $x = $x % $p;
 
    if ($x == 0)
        return 0;
 
    while ($y > 0)
    {
        // If y is odd, multiply
        // x with result
        if ($y & 1)
            $res = ($res * $x) % $p;
 
        // y must be even now
         
        // y = $y/2
        $y = $y >> 1;
        $x = ($x * $x) % $p;
    }
    return $res;
}
 
// Driver Code
$x = 2;
$y = 5;
$p = 13;
echo "Power is ", power($x, $y, $p);
 
// This code is contributed by aj_36
?>


Javascript




// Iterative Javascript program to
// compute modular power
 
// Iterative Function to
// calculate (x^y)%p in O(log y)
function power(x, y, p)
{
    // Initialize result
    let res = 1;
 
    // Update x if it is more
    // than or equal to p
    x = x % p;
 
    if (x == 0)
        return 0;
 
    while (y > 0)
    {
        // If y is odd, multiply
        // x with result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
         
        // y = $y/2
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}
 
// Driver Code
let x = 2;
let y = 5;
let p = 13;
document.write("Power is " + power(x, y, p));
 
// This code is contributed by _saurabh_jaiswal


Output

Power is 6

Time Complexity: O(Log y), where y represents the value of the given input.

Auxiliary Space: O(1), as we are not using any extra space.

Modular exponentiation (Recursive)
 



Previous Article
Next Article

Similar Reads

Modular exponentiation (Recursive)
Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.Examples: Input : a = 2312 b = 34
6 min read
Modular Exponentiation of Complex Numbers
Given four integers A, B, K, M. The task is to find (A + iB)K % M which is a complex number too. A + iB represents a complex number. Examples: Input : A = 2, B = 3, K = 4, M = 5 Output: 1 + i*0 Input : A = 7, B = 3, K = 10, M = 97 Output: 25 + i*29 Prerequisite: Modular Exponentiation Approach: An efficient approach is similar to the modular expone
7 min read
Modular Arithmetic for Competitive Programming
In mathematics, modular arithmetic refers to the arithmetic of integers that wraps around when a certain value is reached, called the modulus. This becomes particularly crucial when handling large numbers in competitive programming. This article "Modular Arithmetic for Competitive Programming" will explore modular arithmetic, its operations, the un
11 min read
Modular Arithmetic
Modular arithmetic is the branch of arithmetic mathematics related to the "mod" functionality. Basically, modular arithmetic is related to the computation of a "mod" of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other. Modular arithmetic, often referred to as "clock a
7 min read
Find Nth term (A matrix exponentiation example)
We are given a recursive function that describes Nth terms in the form of other terms. In this article, we have taken specific examples. [Tex]T_{n} = 2*T_{n-1}+3*T{n-2} \\ Given, T_0=1 T_1=1 [/Tex] Now you are given n, and you have to find out nth term using the above formula. Examples: Input : n = 2 Output : 5 Input : n = 3 Output :13 Prerequisite
11 min read
Expected number of moves to reach the end of a board | Matrix Exponentiation
Given a linear board of length N numbered from 1 to N, the task is to find the expected number of moves required to reach the Nth cell of the board, if we start at cell numbered 1 and at each step we roll a cubical dice to decide the next move. Also, we cannot go outside the bounds of the board. Note that the expected number of moves can be fractio
12 min read
Knuth's Up-Arrow Notation For Exponentiation
Knuth's up-arrow notation, also known as Knuth's arrow notation, is a mathematical notation for exponentiation that was introduced by Donald Knuth in his book "Concrete Mathematics". It uses a sequence of up-arrows (↑) to represent exponentiation with various bases and exponents. Approach: Exponentiation depends on the number of arrows used in the
4 min read
Matrix Exponentiation
This is one of the most used techniques in competitive programming. Let us first consider below simple question. What is the minimum time complexity to find n'th Fibonacci Number? We can find n'th Fibonacci Number in O(Log n) time using Matrix Exponentiation. Refer method 4 of this for details. In this post, a general implementation of Matrix Expon
14 min read
CSES Solutions - Exponentiation II
Your task is to efficiently calculate values a^(b^c) modulo 109+7. Note that in this task we assume that 00 = 1. Examples: Input: N = 2, queries[][] = {{3, 7, 1}, {2, 3, 2}}Output: 2187512Explanation: 3 ^ (7 ^ 1) mod 109+7 = 3 ^ 7 = 21872 ^ (3 ^ 2) mod 109+7 = 2 ^ 9 = 512 Input: N = 3, queries[][] = {{3, 7, 1}, {15, 2, 2}, {3, 4, 5}}Output: 2187506
6 min read
CSES Solutions - Exponentiation
Your task is to efficiently calculate values a^b modulo 109+7. Note that in this task we assume that 00=1. Examples: Input: N = 3, queries[][] = {{3, 4}, {2, 8}, {123, 123}}Output: 81256921450052Explanation: The first query is (3 ^ 4) % (109 + 7) = (3 * 3 * 3 * 3) % (109 + 7) = 81The second query is (2 ^ 8) % (109 + 7) = (2 * 2 * 2 * 2 * 2 * 2 * 2
7 min read
three90RightbarBannerImg