Power Mod

easy math number-theory bit-manipulation 1000 ms · 256 MB

Power Mod

You are given t independent queries. Each query consists of three integers a, b and m. For each query, compute the remainder of a^b divided by m, that is, a^b mod m.

By convention a^0 = 1 for every a, including a = 0.

Input

The first line contains a single integer t (1 ≤ t ≤ 10^5), the number of queries.

Each of the next t lines contains three integers a, b and m (0 ≤ a ≤ 10^18, 0 ≤ b ≤ 10^18, 1 ≤ m ≤ 10^18).

Output

For each query print one line with a single integer: the value of a^b mod m, which lies between 0 and m − 1 inclusive.

Notes

In the first example, 2^10 = 1024 and 1024 mod 1000 = 24; 3^0 = 1 and 1 mod 7 = 1; 5^3 = 125 and 125 mod 13 = 8.

In the second example, any number modulo 1 is 0, even 0^0 = 1. In the last query a = m − 1, which behaves like −1 modulo m, and the exponent is even, so the answer is 1. Note that intermediate products there are far beyond the range of 64-bit integers.

Example 1

Input

3
2 10 1000
3 0 7
5 3 13

Output

24
1
8

Example 2

Input

3
0 0 1
123456789 987654321 1
999999999999999999 1000000000000000000 1000000000000000000

Output

0
0
1

Hints · reveal one at a time if you're stuck

Hint 1

With b as large as 10^18 you cannot multiply a by itself b times. Look at how many squarings it takes to reach an exponent of that size, and what happens to b when you halve it.

Hint 2

Use fast exponentiation: square the base repeatedly and multiply it into the result only for the set bits of b, reducing mod m at every step. Products of two values below 10^18 overflow 64 bits, so widen the multiplication, and remember the answer must be 0 when m is 1.

report an issue Prefer your own editor? sooks prep 21 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.