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));
}
}
这是我从一个网站上找到的代码,可是看不懂。新人!求解释!= =谢谢!
------解决思路----------------------
这段代码是对n!求值后,并且进行缓存了,如果需要很频繁的取n!的值,则这个写法很不错。
如果你第一次需要计算10!,计算好之后,将1-10的阶乘都存放在List中,下次如果是取10以下的数字的阶乘,则直接取,如果大于10,则从10!重新开始计算,并继续缓存在List中。
如果你只是为了计算一次,则大可不必写这么复杂,直接一个循环相乘就完事了。
当然如果数字比较大,用BigInteger是有必要的。
------解决思路----------------------
你把这个问题分成两个部分
1)首先先不使用BigInteger,就用基本数据类型int或者long,自己先试着写一个小程序计算阶乘
做到能运行即可
有问题的话,自己试着调试一下,实在解决不了的时候,把完整的代码和运行结果贴上来
2)1的程序搞定后,找本Java书,看看BigInteger相关的说明以及示例
原来的程序就能秒懂了
------解决思路----------------------
楼上很牛逼的样子,但是我只知道楼主只是想了解下 n! 的算法,不说了,上代码,递归算法:
public static int test(int n){
if(n==1){
return 1;
}else{
return n*test(n-1);
}
}