![]() |
VOOZH | about |
Your task is to efficiently calculate values a^b modulo 109+7. Note that in this task we assume that 00=1.
Examples:
Input: N = 3, queries[][] = {{3, 4}, {2, 8}, {123, 123}}
Output:
81
256
921450052
Explanation:
- The first query is (3 ^ 4) % (109 + 7) = (3 * 3 * 3 * 3) % (109 + 7) = 81
- The second query is (2 ^ 8) % (109 + 7) = (2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) % (109 + 7) = 256
- The third query is (123 ^ 123) % (109 + 7) = 921450052
Input: N = 2, queries[][] = {{4, 3}, {5, 3}}
Output:
64
125
Explanation:
- The first query is (4 ^ 3) % (109 + 7) = (4 * 4 * 4) % (109 + 7) = 64
- The second query is (5 ^ 3) % (109 + 7) = (5 * 5 * 5) % (109 + 7) = 125
Approach: To solve the problem, follow the below idea:
The idea is to uses the concept of binary exponentiation to do this efficiently. If the exponent is even, it squares the result of the base raised to half the exponent. If the exponent is odd, it multiplies the base with the square of the result of the base raised to half the exponent. This is done recursively until t he base case is reached.
Step-by-step algorithm:
Below is the implementation of the algorithm:
81 256 921450052
Time Complexity: O(N * log(M)), where N is the number of queries and M is the maximum value of exponent.
Auxiliary Space: O(1)