为什么这个阶乘方法在1676年后失败了?

时间:2014-12-24 08:14:58

标签: java performance int biginteger

我使用BigInteger制作了一个阶乘方法(由于长度的限制),这是“无限的”,但由于某种原因,当n>时,不会打印返回的值。 1676(返回值为n!)。这是我的代码:

private static BigInteger factorial (int n) {

    //init ans at 1
    BigInteger ans = BigInteger.ONE;

    //multiply ans by decreasing n
    while (n > 1) {
        ans = ans.multiply(BigInteger.valueOf(n--));
    }

    //return ans after loop
    return ans;

}

我使用迭代方法而不是递归方法,因为我不想导致Stackoverflow Exception。 这就是我所知道的:factorial(1676).toString().length() is 4679,在int或甚至短溢出限制之下。 但是,System.out.println(factorial(1676))可以正常工作,而System.out.println(factorial(1677)则不会打印任何内容。 这就是我所知道的,如果可以,请帮助我。

1 个答案:

答案 0 :(得分:0)

Whell,你的算法是正确的,在我的机器下它运行正常。如果您对某些提升感兴趣,可以使用pararell处理。因为你可以把它分成次要因素, 像:

n=1*2*3*4....*(n-1)*n

您可以将此列表拆分为更多子列表:

n! = k*l*h

,其中

k=1*2*....*k
l=(k+1)*(k+2)*...*h
h=(h+1)*...*n

要点是计算子模块然后对它们进行聚合。

这个主题刚才回答: factorial function - parallel processing