问题描述
输入一个正整数n,输出n!的值。
其中n!=1x2x3x…xn。
算法描述
n!可能很大,而计算机能表示的整数范围有限,需要使用高精度计算的方法。使用一个数组A来表示一个大整数a,A[0]表示a的个位,A[1]表示a的十位,依次类推。
将a乘以一个整数k变为将数组A的每一个元素都乘以k,请注意处理相应的进位。
首先将a设为1,然后乘2,乘3,当乘到n时,即得到了n!的值。
输入格式
输入包含一个正整数n,n<=1000。
输出格式
输出n!的准确值。
样例输入
10
样例输出
3628800
分析:数组
代码:
public class Main{
protected static ArrayList A = new ArrayList();
static {
A.add(BigInteger.valueOf(1));//向数组添加1,逻辑大小为1
}
public static synchronized BigInteger factorial(int x) {
//i的初始值为1,此循环用来给数组A存放i!的值
for (int i = A.size(); i <= x; i++) {
BigInteger L = (BigInteger) A.get(i-1);// 得到i-1索引处的值L 1 1 2 6 24 120....(L=(i-1)!)
BigInteger N = L.multiply(BigInteger.valueOf(i));//N=L*i N是索引为i处的值 1 2 6 24 120....(N=i!)
A.add(N);//将i!添加进索引为i的数组A中
}
return (BigInteger) A.get(x);//取出索引为x的值,即x!; 代值计算很好理解的^V^
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
System.out.print(factorial(n));
}
}