高精度快速幂(Java版)

时间:2024-01-18 09:12:26
 import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*; public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
BigInteger a, b, m, ans;
while (cin.hasNext()) {
ans = new BigInteger("1");
a = cin.nextBigInteger();
b = cin.nextBigInteger();
m = cin.nextBigInteger();
a = a.mod(m);
while (b.compareTo(new BigInteger("0")) > 0) {
if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) // if(n%2==1)
ans = ans.multiply(a).mod(m); // sq=(sq*p)%m;
a = a.multiply(a).mod(m); // p=(p*p)%m;
b = b.divide(BigInteger.valueOf(2));
}
System.out.println(ans);
}
}
}