共享共享,我看的一个:import java.math.BigInteger; // Import BigInteger from java.math packageimport java.util.*; // Import all classes (including ArrayList) from java.utilpublic class Factorial4 {
protected static ArrayList table = new ArrayList(); // create cache
static { // Initialize the first element of the cache with !0 = 1.
table.add(BigInteger.valueOf(1));
} /** The factorial() method, using BigIntegers cached in a ArrayList */ public static synchronized BigInteger factorial(int x) { if (x<0) throw new IllegalArgumentException("x must be non-negative."); 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);
}
int result; for(int i=1;i<=n;i++){ result = result*i; }
int result;
for(int i=1;i<=n;i++){
result = result*i;
}
{
public static void main(String args[])
{
int i;
int m=1;
for(i=1;i<=10;i++)
{
m=m*i;
}
System.out.println("阶乘:"+m+"");
}
}
int jiecheng(int i)
{
int s;
if(i==0)
s=1;//是1不是0
else
s=i*jiecheng(i-1)
return s;
}
public class Jiecheng
{
int sum=1;
int i;
public void f(int n)
{
for (i=1;i<n;i++)
sum=sum*i;
System.out.println("i="+i);
System.out.println("n!="+sum);
}
public static void main(String[] args)
{
Jiecheng obj=new Jiecheng();
obj.f(10);
}
}
protected static ArrayList table = new ArrayList();
// create cache
static {
// Initialize the first element of the cache with !0 = 1.
table.add(BigInteger.valueOf(1));
}
/** The factorial() method, using BigIntegers cached in a ArrayList */
public static synchronized BigInteger factorial(int x) { if (x<0)
throw new IllegalArgumentException("x must be non-negative."); 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);
}
for(int i=1;i<=n;i++){
result = result*i;
}
就是一个FOR循环,数据溢出了就换一个数据类型。
StringBuffer rs = new StringBuffer("1");
for (int i = 1; i <= 1000; i++) {
StringBuffer tmp_rs = new StringBuffer();
int carry = 0;
for (int j = 0; j < rs.length(); j++) {
char subnum = rs.charAt(j);
int isubnum = Integer.parseInt(String.valueOf(subnum));
int product = i * isubnum + carry;
int mantissa = product % 10;
carry = product / 10;
tmp_rs.append(mantissa);
}
if (carry != 0)
tmp_rs.append(carry);
rs = tmp_rs;
}
System.out.println(rs.reverse());
}
}
试了1000的阶乘,数了0,个数没错。
tmp_rs.append(carry);这里错了,carry应该反转