THINK FIRST·CODE LATER

← All labs

Fast modular exponentiation

Problem

Write a program that computes aⁿ mod m for several queries using fast (square-and-multiply) exponentiation, so that exponents up to 10¹⁸ are handled in about 60 steps.

Input. The first line holds the number of queries t (1 ≤ t ≤ 100). Each of the next t lines holds three integers a n m with 0 ≤ a ≤ 10¹⁸, 0 ≤ n ≤ 10¹⁸ and 1 ≤ m ≤ 2 000 000 000. By convention a⁰ = 1 (also when a = 0).

Output. One line per query with the value of aⁿ mod m (a number from 0 to m − 1).

Example.

Input:

3
2 10 1000
3 4 5
7 0 13

Output:

24
1
1

Hints: reduce a modulo m first; reduce after every multiplication; with m ≤ 2·10⁹ the product of two remainders is below 4·10¹⁸ and fits in a long. Remember that 1 mod 1 = 0.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d7-1-data-1.txt

3
2 10 1000
3 4 5
7 0 13
What your program must print for d7-1-data-1.txt
24
1
1

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d7-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d7-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.