VOOZH about

URL: https://www.geeksforgeeks.org/dsa/compute-power-of-power-k-times-m/

⇱ Compute power of power k times % m - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Compute power of power k times % m

Last Updated : 11 Jul, 2025

Given x, k and m. Compute (xxxx...k)%m, x is in power k times. Given x is always prime and m is greater than x. 

Examples: 

Input : 2 3 3
Output : 1
Explanation : ((2 ^ 2) ^ 2) % 3 
 = (4 ^ 2) % 3 
 = 1

Input : 3 2 3
Output : 0
Explanation : (3^3)%3 = 0

A naive approach is to compute the power of x k times and do modulus operation every time.  


Output: 
2

 

Time Complexity: O(k * logx), where k and x represents the value of the given integers.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
 

An efficient solution is to use Euler’s Totient Function to solve this problem. Since x is a prime number and is always greater than m, that means x and m will always be co-prime. So the fact that will help here is (a^b)%m = (a^(b % et(m)))%m, where et(m) is Euler Totient Function. Consider having a function calculate(x, k, m) that gives the value (x^x^x^x...k times)%m. (x^x^x^x...k times)%m can be written as (a^b)%m = (a^(b % et(m)))%m, where b = calculate(x, k-1, et(m)). A recursive function can be written, with the base cases when k=0 then, answer is 1, and if m=1, then answer is 0. 

Below is the implementation of the above approach. 


Output: 
0

 

Time Complexity: O(N), where N is 106 since all the Euler Totient values are pre-calculated. 
Auxiliary Space: O(N), where N is 106

Comment