VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-exponentiation-ii/

⇱ CSES Solutions - Exponentiation II - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Exponentiation II

Last Updated : 23 Jul, 2025

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:
2187
512
Explanation:

  • 3 ^ (7 ^ 1) mod 109+7 = 3 ^ 7 = 2187
  • 2 ^ (3 ^ 2) mod 109+7 = 2 ^ 9 = 512

Input: N = 3, queries[][] = {{3, 7, 1}, {15, 2, 2}, {3, 4, 5}}
Output:
2187
50625
763327764

Approach: To solve the problem, follow the below idea:

We can efficiently calculates a^b % mod using the binary exponentiation by squaring technique.

For any positive integer b, a^b can be calculated more efficiently by dividing b by 2 and squaring the result.

  • If b is even, a^b = (a^(b/2)) 2.
  • If b is odd, a^b = a * (a^(b/2)) 2.
  • handling base cases where b is 0 or 1.

Modular Inverse Calculation: We'll use Fermat's Little Theorem, it states that if p is prime and a is not divisible by p, then a^(p-1) ≡ 1 (mod p). The modular inverse of a is a^(p-2) mod p.

Euler's theorem: Since Euler theorem states that aN ≡ aNmodΦ(m) (mod M) so to calculate (a^(b^c)) modulo 109+7 we will calculate ((b ^ c) modulo 109 + 6). To get the final answer, we calculate (a ^ ((b ^ c) % 109+6)) % 109+7

Step-by-step algorithm:

  • Calculate Modular Exponentiation:
    • If the exponent is 0, it returns 1. If the exponent is 1, it returns the base modulo the given value.
    • Recursively computes the result by dividing the exponent by 2 and squaring the result until the exponent is reduced to 0 or 1.
    • If the exponent is even, it squares the result. If the exponent is odd, it multiplies the result by the base after squaring.
  • Calculate (b ^ c) % (109+6) using modular exponentiation and store it in a variable, say power_bc.
  • Calculate (a ^ power_bc) % (109+7) using modular exponentiation and return it as the final answer.

Below is the implementation of the algorithm:


Output
2187
50625
763327764

Time complexity: O(N * log(exponent)), where N is the number of queries.
Auxiliary Space: O(N * log(exponent))

Comment