问题描述
- Java中n!的代码看不懂啊,求解释
-
import java.math.BigInteger;
import java.util.*;
public class Main{
protected static ArrayList table = new ArrayList();
static
{
table.add(BigInteger.valueOf(1));
}
public static synchronized BigInteger factorial(int x)
{
for (int size = table.size(); size <= x; size++)
{
BigInteger lastfact = (BigInteger) table.get(size - 1);
BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
table.add(nextfact);
}
return (BigInteger) table.get(x);
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
System.out.print(factorial(n));
}
}请问这些都是什么意思……新人不是很理解。谢谢!
解决方案
multiply 是乘运算
table 是关键,先求 table 有几个元素,然后加 1.例如: table 初始化只有一个元素,数值为 1. 一次运行: table 只有一个元素,加上 1 后为 2;初始化数值与 2 做乘法。二次运行: table 有两个元素,加 1 后为 3;上次乘的结果,再乘 3...,依次类推完成 N 的阶乘的计算。
解决方案二:
关键是看懂BigInteger这个类,它实现了大数的运算和存储。然后阶乘本身没什么难理解的。
解决方案三:
能 不能有个代码规范。静态代码块是最先执行的,写这个的目的就是给size 赋初值1,后面的你单步调试一下就明白了
解决方案四:
就是求大数的阶乘,主要是BigInteger
时间: 2024-08-04 13:51:22