试题 基础练习 阶乘计算
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
输入一个正整数n,输出n!的值。
其中n!=123*…*n。
算法描述
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 |
关于BigInteger类
java内部的高精度类。
<BigInteger>.add(<Object>);//相加
<BigInteger>.subtract(<Object>);//相减
<BigInteger>.multiply(<Object>);//乘法
<BigInteger>.divide(<Object>);//除法
<BigInteger>.remainder(<Object>);//取余
<BigInteger>.pow(<Object>);//次方
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
BigInteger n=sc.nextBigInteger();
BigInteger ans=new BigInteger("1");
BigInteger cc=new BigInteger("1");
while(n.equals(cc)==false) {
ans=ans.multiply(n);
n=n.subtract(cc);
}
System.out.println(ans);
}
}