hdu5187 java快速幂

特判n==1

 1 import java.io.*;
 2 import java.math.*;
 3 import java.util.*;
 4 import java.text.*;
 5 
 6 public class mydo {
 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 = new BigInteger("2");
13             b = cin.nextBigInteger();
14             m = cin.nextBigInteger();
15             if (b.compareTo(ans)==0) {System.out.println(ans.mod(m)); continue; }
16             a = a.mod(m);
17             while (b.compareTo(new BigInteger("0")) > 0) {
18                 if (b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0) // if(n%2==1)
19                     ans = ans.multiply(a).mod(m); // sq=(sq*p)%m;
20                 a = a.multiply(a).mod(m); // p=(p*p)%m;
21                 b = b.divide(BigInteger.valueOf(2));
22             }
23             a = new BigInteger("2");
24             ans=ans.add(m);
25             ans=ans.subtract(a);
26             System.out.println(ans.mod(m));
27         }
28     }
29 }

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5187

posted on 2015-03-14 23:22  xiao_xin  阅读(123)  评论(0编辑  收藏  举报

导航