The Wayback Machine - https://web.archive.org/web/20240627104138/https://www.geeksforgeeks.org/find-power-power-mod-prime/
Open In App

Find power of power under mod of a prime

Last Updated : 18 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given four numbers A, B, C and M, where M is prime number. Our task is to find ABC (mod M).
Example: 
 

Input  : A = 2, B = 4, C = 3, M = 23
Output : 6
43 = 64 so,
2^64(mod 23) = 6 

 

A Naive Approach is to calculate res = BC and then calculate Ares % M by modular exponential. The problem of this approach is that we can’t apply directly mod M on BC, so we have to calculate this value without mod M. But if we solve it directly then we will come up with the large value of exponent of A which will definitely overflow in final answer.
An Efficient approach is to reduce the BC to a smaller value by using the Fermat’s Little Theorem, and then apply Modular exponential.
 

According the Fermat's little
a(M - 1) = 1 (mod M) if M is a prime.

So if we rewrite BC as x*(M-1) + y, then the
task of computing ABC becomes Ax*(M-1) + y
which can be written as Ax*(M-1)*Ay.
From Fermat's little theorem, we know Ax*(M-1) = 1.
So task of computing ABC reduces to computing Ay

What is the value of y?
From BC = x * (M - 1) + y,
y can be written as BC % (M-1)

We can easily use the above theorem such that we can get
A ^ (B ^ C) % M = (A ^ y ) %  M

Now we only need to find two things as:-
1. y = (B ^ C) % (M - 1)
2. Ans = (A ^ y) % M

 

C++




// C++ program to find (a^b) mod m for a large 'a'
#include<bits/stdc++.h>
using namespace std;
 
// Iterative Function to calculate (x^y)%p in O(log y)
unsigned int power(unsigned int x, unsigned int y,
                                   unsigned int p)
{
    unsigned int res = 1;      // Initialize result
 
    x = x % p;  // Update x if it is more than or
                // equal to 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;
}
 
unsigned int Calculate(unsigned int A, unsigned int B,
                       unsigned int C, unsigned int M)
{
    unsigned int res, ans;
 
    // Calculate B ^ C (mod M - 1)
    res = power(B, C, M-1);
 
    // Calculate A ^ res ( mod M )
    ans = power(A, res, M);
 
    return ans;
}
 
// Driver program to run the case
int main()
{   // M must be a Prime Number
    unsigned int A = 3, B = 9, C = 4, M = 19;
 
    cout << Calculate(A, B, C, M);
 
    return 0;
}


Java




// Java program to find (a^b)
// mod m for a large 'a'
import java.util.*;
 
class GFG {
     
// Iterative Function to
// calculate (x^y)%p in O(log y)
static int power(int x, int y, int p) {
     
    // Initialize result
    int res = 1;
 
    // Update x if it is more
    // than or equal to p
    x = x % p;
 
    while (y > 0) {
         
    // If y is odd, multiply x with result
    if (y % 2 != 0)
        res = (res * x) % p;
 
    // y must be even now
    y = y >> 1; // y = y/2
    x = (x * x) % p;
    }
    return res;
}
 
static int Calculate(int A, int B, int C, int M) {
    int res, ans;
 
    // Calculate B ^ C (mod M - 1)
    res = power(B, C, M - 1);
 
    // Calculate A ^ res ( mod M )
    ans = power(A, res, M);
 
    return ans;
}
 
// Driver code
public static void main(String[] args) {
     
    // M must be a Prime Number
    int A = 3, B = 9, C = 4, M = 19;
 
    System.out.print(Calculate(A, B, C, M));
}
}
 
// This code is contributed by Anant Agarwal.


Python3




# Python program to calculate the ans
def calculate(A, B, C, M):
 
    # Calculate B ^ C (mod M - 1)
    res = pow(B, C, M-1)
 
    # Calculate A ^ res ( mod M )
    ans = pow(A, res, M)
 
    return ans
 
# Driver program to run the case
A = 3
B = 9
C = 4
 
# M must be Prime Number
M = 19
print( calculate(A, B, C, M) )


C#




// C# program to find (a^b) mod m for
// a large 'a'
using System;
 
class GFG {
     
    // Iterative Function to calculate
    // (x^y)%p in O(log y)
    static int power(int x, int y, int p)
    {
         
        // Initialize result
        int res = 1;
     
        // Update x if it is more
        // than or equal to p
        x = x % p;
     
        while (y > 0) {
             
            // If y is odd, multiply x
            // with result
            if (y % 2 != 0)
                res = (res * x) % p;
         
            // y must be even now
            y = y >> 1; // y = y/2
            x = (x * x) % p;
        }
        return res;
    }
     
    static int Calculate(int A, int B,
                          int C, int M)
    {
        int res, ans;
     
        // Calculate B ^ C (mod M - 1)
        res = power(B, C, M - 1);
     
        // Calculate A ^ res ( mod M )
        ans = power(A, res, M);
     
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
         
        // M must be a Prime Number
        int A = 3, B = 9, C = 4, M = 19;
     
        Console.Write(Calculate(A, B, C, M));
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP program to find
// (a^b) mod m for a
// large 'a'
 
// Iterative Function
// to calculate (x^y)%p
// in O(log y)
function power($x, $y, $p)
{
    $res = 1; // Initialize result
 
    $x = $x % $p; // Update x if it
                  // is more than or
                  // equal to 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;
}
 
function Calculate($A, $B, $C, $M)
{
    $res; $ans;
 
    // Calculate B ^ C
    // (mod M - 1)
    $res = power($B, $C, $M - 1);
 
    // Calculate A ^
    // res ( mod M )
    $ans = power($A, $res, $M);
 
    return $ans;
}
 
// Driver Code
 
// M must be
// a Prime Number
$A = 3; $B = 9;
$C = 4; $M = 19;
 
echo Calculate($A, $B, 
               $C, $M);
 
// This code is contributed
// by ajit
?>


Javascript




<script>
 
// Javascript program to find (a^b)
// mod m for a large 'a'
  
// 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; 
   
    while (y > 0) {
           
    // If y is odd, multiply x with result
    if (y % 2 != 0)
        res = (res * x) % p;
   
    // y must be even now
    y = y >> 1; // y = y/2
    x = (x * x) % p;
    }
    return res;
}
   
function Calculate(A, B, C, M) {
    let res, ans;
   
    // Calculate B ^ C (mod M - 1)
    res = power(B, C, M - 1);
   
    // Calculate A ^ res ( mod M )
    ans = power(A, res, M);
   
    return ans;
}
 
// Driver Code
     
    // M must be a Prime Number
    let A = 3, B = 9, C = 4, M = 19;
   
    document.write(Calculate(A, B, C, M));
     
</script>


Output: 

18

Time Complexity: O(log(B) + log(C)) 
Auxiliary space: O(1)

 



Previous Article
Next Article

Similar Reads

Count numbers in a given range having prime and non-prime digits at prime and non-prime positions respectively
Given two integers L and R, the task is to find the count of numbers in the range [L, R] having prime digits at prime positions and non-prime digits at non-prime positions. Examples: Input: L = 5, R = 22 Output: 7Explanation: The numbers 6, 8, 9, 12, 13, 15, and 17 have prime digits at prime positions and non-prime digits at non-prime positions. In
15 min read
Find value of y mod (2 raised to power x)
Given two positive integer x and y. we have to find the value of y mod 2x. That is remainder when y is divided by 2x. Examples: Input : x = 3, y = 14 Output : 6 Explanation : 14 % 23 = 14 % 8 = 6. Input : x = 4, y = 14 Output : 14 Explanation : 14 % 24 = 14 % 16 = 14. To solve this question we can use pow() and modulo operator and can easily find t
7 min read
Find value of (1^n + 2^n + 3^n + 4^n ) mod 5
You are given an positive integer n. You have to find the value of (1n +2n + 3n + 4n ) mod 5. Note : Value of n may be very large of order 1015. Examples: Input : n = 4Output : 4Explanation : (14 + 24 + 34 + 44)mod 5 = (1+16+81+256)mod 5 = 354 mod 5 = 4 Input : n = 2Output : 0Explanation : (12 + 22 + 32 + 42)mod 5 = (1+4+9+16)mod 5 = 30 mod 5 = 0 B
4 min read
Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n
You are given a function f(n) = (n1 + n2 + n3 + n4), you have to find the value of f(n) mod 5 for any given value of positive integer n. Note: n may be large enough, such that f(n) &gt; 1018. Examples : Input : n = 4Output : 0Explanation : f(4) = 4 + 16 + 64 + 256 = 330, f(4) mod 5 = 330 mod 5 = 0. Input : n = 1 Output : 4Explanation : f(1) = 1 + 1
5 min read
Find (1^n + 2^n + 3^n + 4^n) mod 5 | Set 2
Given a very large number N. The task is to find (1n + 2n + 3n + 4n) mod 5.Examples: Input: N = 4 Output: 4 (1 + 16 + 81 + 256) % 5 = 354 % 5 = 4Input: N = 7823462937826332873467731 Output: 0 Approach: (1n + 2n + 3n + 4n) mod 5 = (1n mod ?(5) + 2n mod ?(5) + 3n mod ?(5) + 4n mod ?(5)) mod 5. This formula is correct because 5 is a prime number and i
5 min read
Count array elements having modular inverse under given prime number P equal to itself
Given an array arr[] of size N and a prime number P, the task is to count the elements of the array such that modulo multiplicative inverse of the element under modulo P is equal to the element itself. Examples: Input: arr[] = {1, 6, 4, 5}, P = 7Output: 2Explanation:Modular multiplicative inverse of arr[0](=1) under modulo P(= 7) is arr[0](= 1) its
5 min read
Divide two integers without using multiplication, division and mod operator | Set2
Given two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator.Examples: Input: a = 10, b = 3Output: 3 Input: a = 43, b = -8Output: -5 This problem has been already discussed here. In this post, a different approach is discussed.Approach : Let a/b = c.Take log on both sideslog(a) - lo
7 min read
Solve Linear Congruences Ax = B (mod N) for values of x in range [0, N-1]
Given three positive integers A, B, and N, which represent a linear congruence of the form AX=B (mod N), the task is to print all possible values of X (mod N) i.e in the range [0, N-1] that satisfies this equation. If there is no solution, print -1. Examples: Input: A=15, B=9, N=18Output: 15, 3, 9Explanation: The values of X satisfying the conditio
9 min read
Divide two integers without using multiplication, division and mod operator
Given two integers say a and b. Find the quotient after dividing a by b without using multiplication, division, and mod operator. Example: Input : a = 10, b = 3Output : 3 Input : a = 43, b = -8Output : -5 Recommended PracticeDivision without using multiplication, division and mod operatorTry It! Approach: Keep subtracting the divisor from the divid
15+ min read
Minimum steps to reach end from start by performing multiplication and mod operations with array elements
Given start, end and an array of N numbers. At each step, start is multiplied with any number in the array and then mod operation with 100000 is done to get the new start. The task is to find the minimum steps in which end can be achieved starting from start. Examples: Input: start = 3 end = 30 a[] = {2, 5, 7} Output: 2 Step 1: 3*2 = 6 % 100000 = 6
15+ min read
three90RightbarBannerImg