题目要求1!+2!+3!+4!+...+100000000000000000000000000000000!
一下是我的代码:哪里有问题啊!
//这个程序那里错了
import java.util.*;
import java.math.*;
public class Test5 {
static BigInteger fun1(BigInteger n)
{
BigInteger i;
BigInteger result=1;
for(i=1;i.subtract(n)!=0;i.add(1))
{
result=result.multiply(i);
}
return result;
}
static BigInteger fun(BigInteger n)
{
BigInteger result =0;
BigInteger i=BigInteger.valueOf(1);
for(;i.subtract(n)!=0;i.add(1))
{
result=result.add(fun(i));
}
return result;
}
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
int i = cin.nextInt();
BigInteger n = BigInteger.valueOf(i);
System.out.println(fun(i));
}
}

解决方案 »

  1.   

    数字太大了用BigIntege肯定不行。
      

  2.   

    下面这个阶乘算法是经过调整过的,减少了很多乘法次数,计算 99999! 大概需要 14~15 秒钟,但是结果输出太慢了!import java.math.BigInteger;public class BigFactorial {    public static void main(String args[]) {
            long t0, t1;
            t0 = System.currentTimeMillis();
            BigInteger bi = factorial(99999);
            t1 = System.currentTimeMillis();
            System.out.println(t1 - t0);
        }    public static BigInteger factorial(int n) {
            if(n < 2) {
                return BigInteger.ONE;
            }
            int[] oddCount = new int[Integer.numberOfTrailingZeros(Integer.highestOneBit(n))];
            int shift = init(oddCount, n);
            BigInteger result = BigInteger.ONE;
            BigInteger bg = BigInteger.ONE;
            BigInteger tmp = BigInteger.ONE;        int max = oddCount[oddCount.length - 1];
            int offset = (oddCount[0] + 1) & 1;
            int oddStart = 1;
            while(oddStart <= max) {
                tmp = tmp.multiply(new BigInteger(String.valueOf(2 * oddStart + 1)));
                if(oddCount[offset] == oddStart) {
                    offset++;
                    bg = bg.multiply(tmp);
                    tmp = BigInteger.ONE;
                    result = result.multiply(bg);
                }
                oddStart++;
            }
            return result.shiftLeft(shift);
        }    private static int init(int[] oddCount, int n) {
            int s = n;
            int r = 0;
            int k = oddCount.length;
            while(k > 0) {
                s >>= 1;
                oddCount[--k] = n - s - 1;
                n = s;
                r += s;
            }
            return r;
        }
    }
      

  3.   

    99999! 用 Stirling 公式计算出来的大概值为 2.824227054182054 * 10^456568这是一个拥有 45 万多位的数字!
      

  4.   

    啊··我最讨厌的就是这种伤害CPU的题目了··