![]() |
VOOZH | about |
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:
Below is the implementation of the algorithm:
2187 50625 763327764
Time complexity: O(N * log(exponent)), where N is the number of queries.
Auxiliary Space: O(N * log(exponent))