You are given three positive integers ‘A’, ‘B’, and ‘M’. Your task is to find out the result of ‘A^B’ mod ‘M’.
This task was too easy for Ninja, and being a top-class ninja, he likes to make things a little difficult in order to enjoy solving them. So he converted B into base 3 and is now trying to find the answer.
But it seems like he made the task a little too difficult for himself. Being a good friend of Ninja, can you help find him ‘A^B mod M’ when ‘A’, ‘M’ is given in base 10 and ‘B’ is in base 3?
Input Format :
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the ‘T’ test cases follow.
The first line of each test case contains three positive integers, ‘A’, ‘B’, and ‘M’ respectively.
Output Format :
For each test case, print a single positive integer, the value of ‘A^B’ mod ‘M’.
The output of each test case will be printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= A <= 10^6
1 <= M <= 10^6
1 <= |B| <= 250
Where |B| is the number of digits of ‘B’ in base 3.
Time Limit: 1 sec
1
2 11 6
4
‘B’ is ‘10’ in base 3 which is equal to 4 in base 10. Hence the answer is 2^4 mod 6 which is equal to 4.
2
5 201 7
6 120 9
5
0
For test case 1, ‘B’ equals 19 in base 10. 5^19 mod 7 = 5.
For test case 1, ‘B’ equals 15 in base 10. 6^15 mod 9 = 0.
Try to find the answer without computing the exact value of B.
O(N), where N is the length of B.
We are only traversing the string B. Hence the time complexity is O(N).
O(1)
As we are using constant extra space.