找一个大数字的阶乘

时间:2015-09-26 12:48:53

标签: java biginteger factorial

我有一些方法可以找到大数的因子。有人可以解释一下,它有什么问题以及为什么我没有输出?

public static long factorial(long num) {
    BigInteger numm = BigInteger.valueOf(num);
    BigInteger fact= BigInteger.valueOf(1);
    for (; numm.compareTo(BigInteger.ZERO)==1 ; fact = fact.multiply(numm)) {
        numm.subtract(BigInteger.ONE);
    }
    return fact.longValue();
}

2 个答案:

答案 0 :(得分:0)

我不认为你是如何写一个阶乘的。当你返回BigInteger时,为什么要使用long?所以,只需做出决定,longBigInteger。我会选择BigInteger,因为你说你想要操作非常大的数字。你应该使用递归来做析因。

public BigInteger factorial (BigInteger number) {
    if (number.equals(BigInteger.ONE) || number.equals(BigInteger.ZERO)) {
        return BigInteger.ONE;
    }
    return number.multiply(factorial(number.subtract(BigInteger.ONE)));
}

答案 1 :(得分:0)

您不能将减法值分配给numm。这就是问题。 要继续使用代码,请使用num + 1,因为for循环的最后一部分在减法后执行。所以,需要一次额外的迭代。

检查:

long num=5;
BigInteger numm = BigInteger.valueOf(num + 1);
BigInteger fact= BigInteger.valueOf(1);
for (; numm.compareTo(BigInteger.ONE)==1 ; fact = fact.multiply(numm)) {
    numm = numm.subtract(BigInteger.ONE);
}
System.out.println(fact.longValue());
相关问题