高精度快速幂(Java版)

 1 import java.io.*;
 2 import java.math.*;
 3 import java.util.*;
 4 import java.text.*;
 5 
 6 public class Main {
 7     public static void main(String[] args) {
 8         Scanner cin = new Scanner(System.in);
 9         BigInteger a, b, m, ans;
10         while (cin.hasNext()) {
11             ans = new BigInteger("1");
12             a = cin.nextBigInteger();
13             b = cin.nextBigInteger();
14             m = cin.nextBigInteger();
15             a = a.mod(m);
16             while (b.compareTo(new BigInteger("0")) > 0) {
17                 if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) // if(n%2==1)
18                     ans = ans.multiply(a).mod(m); // sq=(sq*p)%m;
19                 a = a.multiply(a).mod(m); // p=(p*p)%m;
20                 b = b.divide(BigInteger.valueOf(2));
21             }
22             System.out.println(ans);
23         }
24     }
25 }
posted @ 2014-07-20 00:56  Desgard_Duan  阅读(420)  评论(0编辑  收藏  举报