You are given four integers ‘A’, ‘B’, ‘C’, ‘M’ your task is to find ( ‘A’ ^ ‘B’ / ‘C’) % ‘M’.
Note: Greatest Common Divisor (gcd) of ‘C’ and ‘M’ will always be 1.
For Example:
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.
Output Format:
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.
Note:
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.
2
6 2 3 7
2 4 8 7
5
2
For the first test case,
a ^ b / c = 36 / 3, which is 12.
So, 12 % 7 is 5, hence the output is 5.
For the second test case,
a ^ b / c = 16 / 8, which is 2.
So, 2 % 7 is 2, hence the output is 2.
2
10 5 9 8
2 10 7 10
0
2
Use modular multiplicative inverse.
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:
O( max(M, B) ), where M and B are the given integers.
Since we are iterating over B during calculating (A ^ B) % M and iterating over M during multiplicative modular inverse calculation, the overall time complexity will be max(M, B).
O(1).
Constant space is used.