【问题标题】:Difficulty with BigIntegerBigInteger 的困难
【发布时间】:2015-12-23 21:58:01
【问题描述】:

我正在尝试使用 Recursion 和 BigInteger 进行阶乘,但 eclipse 抱怨 BigInteger。我知道这个程序应该很简单,但它让我头疼。这是代码。

import java.util.Scanner;
import java.math.BigInteger;

public class Factorial
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter integer");
        BigInteger n = input.nextBigInteger();
        System.out.println("Factorial of " + n + " is "  + fact(n));

    }

    public static  int fact(BigInteger n)
    {
        if(n ==0)
        {
            return 1;
        }
        else
        {
            return n * fact(n-1);
        }
    }
}

【问题讨论】:

    标签: java biginteger factorial


    【解决方案1】:

    BigInteger 不支持使用== 进行比较和使用* 进行乘法运算。相反,您必须调用 BigInteger 类的适当方法(equals()multipy())。

    还要注意存在BigInteger.ZEROBigInteger.ONE

    最后,您的fact 方法的返回类型 应该是BigInteger 而不是int。您是否希望 参数BigIntegerint 类型取决于您。

    【讨论】:

    • 另外,您的factorial 方法可能应该接受int 并返回BigInteger,而不是相反。
    【解决方案2】:

    除了 @aix 提到的关于在 BigInteger 上调用算术的内容之外 - 我还可以看到此代码的另一个问题。

    你的方法签名是

    public static  int fact(BigInteger n)
    

    这是有问题的——阶乘增长很快,所以你很可能会溢出结果。
    认为你真正想要的是:

    public static  BigInteger fact(int n)
    

    这更有意义,因为返回值可能应该是 BigInteger(因为它增长很快)而不是参数,或者可能是两者。

    【讨论】:

      【解决方案3】:

      Java 不支持运算符重载。因此,用户定义的类不支持 + 和 ==,只有一个例外是 java.lang.String 支持 +。

      【讨论】:

        【解决方案4】:

        我相信你不能简单地在 BigInteger 对象上使用算术运算符。尝试将他们的方法用于算术过程,例如比较、减法、乘法等。

        参考文献给出here

        【讨论】:

          猜你喜欢
          • 2019-07-16
          • 2017-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多