用java语言写一道数学题

来源:百度知道 编辑:UC知道 时间:2024/05/24 00:51:26
用java语言写出:1000!
(1000的阶乘:1000*999*998*……*3*2*1).
public class jiesheng{
public static void main(String[]args){
//你的答案
}
}

//这个题难点在大数.因为1000的阶乖十在太大了.所以必须用BigInteger.
//楼上那种算法是不对的.这题看起来简单,其实要比想象中麻烦和难.

import java.math.BigInteger;
import java.util.*;
public class jiesheng{
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){
System.out.print(factorial(1000));
}
}

BigInteger x= BigInteger.ONE;
for(long i=2; i<=1000; i++)
{
x = x.multiply(BigInteger.valueOf(i));
}
System