
A = 2, B = 2, C = 3, M = 5
Computing B ^ C gives 2 ^ 3 = 8, Now A ^ (B ^ C) = 2 ^ 8 = 256. 256 Mod 5 is 1. Hence the final answer is 1.
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then each test cases follow.
The first line of each test case contains four space-separated integers A, B, C, and M.
For each test case, print a single integer ‘ans’.
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 and return the answer.
1 <= T <= 100
1 <= A, B, C <= 10^9
1 < M <= 10^9 + 7
Time limit: 1 sec
According to Fermat’s theorem, A ^ (K - 1) = 1 (Mod K) if K is a Prime Number.
So we will try to convert A ^ (B ^ C) mod M to A ^ (t * (M - 1) + y) i.e. Convert B ^ C to
t * (M - 1) + y. By doing this, A ^ (t * (M - 1) + y) can be written as (A ^ (t * (M - 1)) * (A ^ (y)).
And according to Fermat's theorem, A ^ (t * (M - 1)) = 1 (Mod M).
So the final answer we have to compute is (A ^ y) Mod M, Where y is (B ^ C) Mod (M - 1).
The steps are as follows: