Find power of power under mod of a prime in C++


In this problem we are given four values A, B, C, M(a prime number). Our task is to Find power of power under mod of a prime.

We simply need to find the value of (A ^ (B ^ C)) (mod M).

Let’s take an example to understand the problem,

Input

A = 3, B = 6, C = 2, M = 11

Output

3

Explanation

(A ^ (B ^ C)) = (3 ^ (6 ^ 2)) = (3 ^ (36))(mod 11) = 3

Solution Approach

A simple solution to the problem is by directly calculating the values of the (A ^ (B ^ C)) , which is done by first calculating the value of (B^C) and then (A ^ (B ^ C)) then taking its mod. (B^C) will result in a huge figure storing which can be a task. And the calculation might lead to overflow.

So, a more efficient approach would be using the fermat’s Little Theorem to find the values.

The theorem is,

a^(m-1) = 1 (mod M) where m is a prime number.

Using this we will convert bc of our problem to a number of the form,

x*(M-1) + y, for our given value of M.

Using the fermat's theorem, the part A^(x*(M-1)) becomes 1.

This will reduce the calculation to, finding the value of Ay.

The value of y can be calculated as,

Bc = x*(M-1) + y

This makes y the remainder left when we divide Bc by (M-1),

So, y = Bc % (M-1)

This makes the result alot easy as we need to find,

(A ^ ((B^C) %( M-1)) % M

Program to illustrate the working of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int calcPowerMod(int x, int y, int p) {
   int powMod = 1;
   x = x % p;
   while (y > 0) {
      if (y & 1)
         powMod = (powMod*x) % p;
      y /=2; // y = y/2
      x = (x*x) % p;
   }
   return powMod;
}
int findPowerOfPowerMod(int A, int B, int C, int M) {
   return calcPowerMod(A, calcPowerMod(B, C, M-1), M);
}
int main() {
   int A = 3, B = 6, C = 2, M = 11;
   cout<<"The power of power under modulo is "<<findPowerOfPowerMod(A, B, C, M);
   return 0;
}

Output

The power of power under modulo is 3

Updated on: 16-Mar-2021

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements