如何在Java中正确使用BigInteger方法?

如何在Java中正确使用BigInteger方法?,java,Java,我尝试使用以下方法对一个数字进行阶乘: public static BigInteger factorial (long n) { BigInteger result = BigInteger.ONE; for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) { result = result.multiply

我尝试使用以下方法对一个数字进行阶乘:

public static BigInteger factorial (long n) {
    BigInteger result = BigInteger.ONE;
    for(BigInteger i = BigInteger.TWO; i.compareTo(BigInteger.valueOf(n)) >= 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(i);
    }
    return result;
}
我在问为什么te结果总是保持1(BigInteger.1)?

参见

返回:一个负整数、零或正整数,因为此对象小于、等于或大于指定对象

您正在使用
=0
表示在
i
大于
n
时继续循环

您可能需要

是错的,改用

i.compareTo(BigInteger.valueOf(n)) <= 0

i.compareTo(BigInteger.valueOf(n))您在这里期望什么行为?result=result*i;最终结果必须是n!到目前为止,理解这类事情的最好方法是使用IDE中内置的调试器逐语句地逐步完成代码语句。您调试了吗?循环实际执行了多少次?
i.compareTo(BigInteger.valueOf(n)) <= 0