描述
我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它?
输入
输入一个整数m(0<m<=5000)
输出
输出m的阶乘,并在输出结束之后输入一个换行符
样例输入
50
样例输出
30414093201713378043612608166064768844377641568960512000000000000
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入n:");
Integer num = null;
try {
num = Integer.parseInt(sc.nextLine());
}catch (NumberFormatException e){
throw new RuntimeException("请输入数字");
}catch (Exception e){
e.printStackTrace();
}
if(num < 0){
throw new RuntimeException("输入大于等于0的数据");
}
if (num > 15){
System.out.println(getBigFac(num));
return;
}
System.out.println(getFac(num));
}
public static long getFac(Integer n) {
if (n == 1) {
return 1;
}
return getFac(n - 1) * n;
}
public static BigInteger getBigFac(Integer n) {
BigInteger num = new BigInteger("1");
for(int i = 1; i <=n;i++){
num =num.multiply(new BigInteger(i + ""));
}
return num;
}