日期:2014-05-20 浏览次数:20781 次
public class Test2 { private class BigInt{ public long a=0;//最低位 public long b=0; public long c=0; public long d=0;//最高位 } /** * 20以下的乘方 * @param num (long) 大于1小于等于20的整数 * @return BigInt */ private BigInt power(long num){ BigInt result = new BigInt(); if(num>=1 && num<=20){ result.a=1L;//起始值为1,作为基数用于计算乘方 for(int i=0;i<num;i++){ result.a*=num; result.b*=num; result.c*=num; result.d*=num; result.b+=result.a/100000000; result.c+=result.b/100000000; result.d+=result.c/100000000; result.c%=100000000; result.b%=100000000; result.a%=100000000; } } return result; } /** * 加法 * @param num1 (BigInt) 第一个数 * @param num2 (BigInt) 第二个数 * @return BigInt */ private BigInt add(BigInt num1,BigInt num2){ BigInt result = new BigInt(); if(num1!=null && num2!=null){ result.a=num1.a+num2.a; result.b=num1.b+num2.b; result.c=num1.c+num2.c; result.d=num1.d+num2.d; result.b+=result.a/100000000; result.c+=result.b/100000000; result.d+=result.c/100000000; result.c%=100000000; result.b%=100000000; result.a%=100000000; } return result; } /** * 计算 * @param num (long) 大于1小于等于20的整数 * @return String */ public String compute(long num){ String result = ""; if(num>=1 && num<=20){ BigInt bigNum = new BigInt(); for(long i=0;i<num;i++){ bigNum = add(bigNum,power(i+1L)); } result = String.format("%08d", bigNum.d);//格式化成8位数字,不足用0补位 result += String.format("%08d", bigNum.c); result += String.format("%08d", bigNum.b); result += String.format("%08d", bigNum.a); result = result.replaceAll("^0+", "");//去掉首位的0 }else{ result = "输入不合要求!"; } return result; } public static void main(String args[]){ System.out.println(new Test2().compute(10L)); } }