Euler's Exponents
Tag(s):

## Medium, Modular exponentiation

Problem
Editorial
Analytics

Given four numbers $A$ , $B$ , $C$ and $P$ where $P$ is prime number .

## ( A B C ) % P = ( A ( B C ) % phi(P) ) % P

where $phi(P)$ is the Euler's Totient Function of $P$ .

However the equation is restricted only to the prime numbers.

Write a program to solve this problem if the given $P$ is not $Prime$ .

Input Format
First line of input contains a single integer $T$ denoting the number of test cases. First and the only line of each test case contains four space separated $A$ , $B$ , $C$ and $P$.

Output Format
For each test case , Print the required answer .

Input Constraint
$1 ≤ T ≤ 10$
$1 ≤ A ≤ 10^9$
$1 ≤ B ≤ 10^9$
$1 ≤ C ≤ 10^5$
$1 ≤ P ≤ 10$$18$

SAMPLE INPUT
2
3 3 3 777
3 5 2 10

SAMPLE OUTPUT
258
3


Explanation

Test 1 : A = 3 B = 3 C = 3 P = 777 (A^(B^C)) %P = 258 Test 2 : A = 3 B = 5 C = 2 P = 10 (A^(B^C)) %P = 3

Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
Marking Scheme: Marks are awarded when all the testcases pass.
Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Visual Basic

## CODE EDITOR

Initializing Code Editor...
Your Rating:

## This Problem was Asked in

Challenge Name

Relapse_2

OTHER PROBLEMS OF THIS CHALLENGE
Notifications

?