Compute power of power k times % m


Our objective to compute power of power k time % m, with the values of base, k and m provided as input −

Look at the image above. Have you ever tried to compute such a problem? Let’s try it.

Compute the power of power k times and then find modulo with m.

Explanation

In this question, x, k, and m are given. Compute ${x^{x{^x{^{^.{^{^.{^{^.}}}}}}}}}$ up to k times and then modulo with m.

Let’s understand with an example.

Given, x = 2, k = 4, and m = 6

So, Compute $2^{2^{2{^2}}}\:=\:4^{2{^2}}\:=\:16^2\:=\:256$

Then 256 % 6 = 4.

So, the final outcome is 4.

Approach

Let’s discuss the step-by-step algorithm to compute the power of power k times % m.

  • Take the value of x, k, and m as input.

  • Compute power of power using the pow function and finally use the modulo operator to get the final outcome.

  • Print the final outcome as output.

C++ program to compute power of power k times % m.

#include <iostream>
#include <cmath>
using namespace std;

int powofpow(int x, int k){
   int val = x;
   k--;
   while (k--)
      val = pow(val, x);
 
   return val;
}

int main(){
   int x = 5, k = 2, m = 3;
   int result;
   
   result =  powofpow(x, k);
   result %= m;
   
   cout << "Compute power of power " << k << " times % " << m << " of " << x << " is " << result << endl;
   
   return 0;
}

Output

Compute power of power 2 times % 3 of 5 is 2

Complexities

Time complexity: O(k), As this code performs an iteration (k-1) times.

Space complexity: O(1), As the code uses a fixed number of variables to store input values and results, regardless of the size of the input.

Conclusion

In this article, we have tried to explain the approach to compute the power of power k times % m, with the values of base, k, and m given as input. I hope this article helps you to learn the concept in a better way.

Updated on: 23-Mar-2023

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements