


For ‘A’ = 4, ‘B’ = 2, ‘C’ = 4, ‘M’ = 3,
‘A’ ^ ‘B’ / ‘C’ = 16 / 4, which is 4.
So, 4 % 3 is 1, hence the output will be 1.
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case contains four space-separated integers ‘A’, ‘B’, ‘C’, ‘M’, representing the integers described in the problem statement.
For each test case, print an integer representing the task defined in the problem statement.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10^4
1 <= A, B, C, M <= 10^9
Time Limit: 1 sec.
Let’s break the task into simpler tasks. We can easily calculate (A ^ B) % M, but note that ( X / Y) % Z is not equal to ( ( X % Z ) / ( Y % Z ) ) % Z. We have to calculate modular multiplicative inverse for division operation. So we have to find an integer, say ‘INV’ such that ‘INV’ * C = 1 % M.
More details about modular multiplicative inverse can be found at the given link:
https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
Algorithm:
We will use modular exponentiation to calculate (A ^ B) % M in logarithmic time complexity. To calculate (C^ -1) % M, we will use the Extended Euclidean Algorithm.
The main idea of the algorithm is that two integers C and M can be represented as
C * X + M * Y = gcd(C, M), where X and Y are two integers. In this case, gcd(C, M) is 1.
More details about the Extended Euclidean Algorithm can be found at the given link:
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Algorithm: