Modular Exponentiation (Fast Power)
Problem
Read a, b and m. Print (a to the power b) mod m. The exponent b can be as large as 10^15, so you can not multiply b times. Use fast exponentiation.
Constraints
- 0 <= a, b <= 10^15
- 1 <= m <= 10^9
Examples
Input
2 10 1000
Output
24
Solutions
We split the exponent in binary. For each bit we square the base, and we multiply the result when the bit is 1. The mod after every multiplication keeps numbers small. This takes log2(b) steps.
/*
* Problem : Compute a^b mod m quickly.
* Input : Three integers a, b, m.
* Output : a^b mod m.
* Approach: Square the base and halve the exponent.
* Time : O(log b)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(long a, long b, long m) {
// Step 1: The result starts at 1. Keep the base smaller than m.
long result = 1 % m;
long base = a % m;
long exponent = b;
// Step 2: Repeat until the exponent is 0.
while (exponent > 0) {
// Step 3: If the exponent is odd, multiply the result by the base. Take mod after each multiplication.
if (exponent % 2 == 1) {
result = result * base % m;
}
// Step 4: Square the base and halve the exponent.
base = base * base % m;
exponent = exponent / 2;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
long m = scanner.nextLong();
System.out.println(solve(a, b, m));
}
}
Hints (2)
- What is a^8 if you know a^4?
- Why take mod after every step?