# 算法 ： 算法导论学习之补漏:高精度幂运算

### 求高精度幂

Time Limit: 500MS Memory Limit: 10000K Total Submissions: 157463 Accepted: 38343 Description

T输入包括多组 R 和 n。 R 的值占第 1 到第 6 列，n 的值占第 8 和第 9 列。

Output

Sample Input

95.123 12 0.4321 20 5.1234 15 6.7592 9 98.999 10 1.0100 12 Sample Output

548815620517731830194541.899025343415715973535967221869852721 .00000005148554641076956121994511276767154838481760200726351203835429763013462401 43992025569.928573701266488041146654993318703707511666295476720493953024 29448126.764121021618164430206909037173276672 90429072743629540498.107596019456651774561044010001 1.126825030131969720661201

``    import java.io.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Scanner;  /**  * Created by zhaomingwei on 2016/3/10.  */ public class BigDec2 { public static void main(String[] args) throws IOException {     //接收输入数组:     List inStrs  = new ArrayList();     //输入     Scanner scanner = new Scanner(System.in);     //输入数据     String inStr = scanner.nextLine();     //windows下换行符  f**k     while(!("/r/n".equals(inStr)||"//n".equals(inStr)||inStr.trim().length()<9)){         inStrs.add(inStr);         inStr = scanner.nextLine();     }      for(int i = 0; i<inStrs.size(); i++){         String str = (String) inStrs.get(i);         //判断格式         if (str.length()!=9){             System.out.println("输入字符串格式错误!长度应该为9,实际为:"+str.length());             return;         }         //R 和 n         String inDouble = str.substring(0,6);         String nInt = str.substring(7,9);         if(inDouble==null){             System.out.println("输入字符串格式错误!");             return;         }         if(nInt==null){             System.out.println("输入字符串格式错误!");             return;         }          //转化为对应的 BigDecimal 和 int 类型         BigDecimal bigDecR = new BigDecimal(inDouble.trim());         int n = Integer.parseInt(nInt.trim());          //判断范围是否合理         if (bigDecR.compareTo(BigDecimal.valueOf(99.999)) >= 0                 || bigDecR.compareTo(BigDecimal.valueOf(0))<=0){             System.out.println("R的范围错误,请输入范围在(0<R<99.999): "+bigDecR);             return;         }         if (n>25||n<0){             System.out.println("n范围错误请输入范围在(0<R<25): "+n);             return;         }          //做乘方         BigDecimal powerResult = bigDecR.pow(n);         //也可以自己写乘方算法         //BigDecimal powerResult = power(bigDecR,n);         //去除科学计数法         String strResult = powerResult.toPlainString();         strResult = strResult.replaceAll("^0+","").replaceAll("//.0+\$","");         //去除前导0 ^0+  和 整数小数点 /.0+\$  后面不需要的0 ./         if (strResult.contains(".")){             strResult = strResult.replaceAll("0+\$","");         }         System.out.println(strResult);     }  }  public static BigDecimal power(BigDecimal decimal,int n){     BigDecimal result = new BigDecimal(1.0);     for(int i=0; i<n; i++){         result = result.multiply(decimal);     }      return result; } } ``