Difficulty with BigInteger

◇◆丶佛笑我妖孽 提交于 2020-01-11 06:50:11

问题


I am trying to do Factorial with Recursion and BigIntegers but eclipse is complaining about the BigInteger. I know the program is supposed to be simple but it is giving me headache. Here is the code.

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);
        }
    }
}

回答1:


BigInteger does not support comparison using == and multiplication using *. Instead, you have to call the appropriate methods of the BigInteger class (equals() and multipy()).

Also note that there exist BigInteger.ZERO and BigInteger.ONE.

Finally, the return type of your fact method should be BigInteger and not int. Whether you want the argument to be of type BigInteger or int is up to you.




回答2:


In addition to what @aix mentioned regarding invoking the arithmetics on BigInteger - I can also see another issue with this code.

Your method signature is

public static  int fact(BigInteger n)

This is problemantic - factorial grows fast, so you are very likely to overflow the result.
I think what you realy wanted is:

public static  BigInteger fact(int n)

which makes much more sense, since the return value should probably be the BigInteger (since it grows fast) and not the parameter, or possibly - both of them.




回答3:


Java doesn't support operator overloading. So + and == can't be supported for user-defined classes with one exception that java.lang.String supports +.




回答4:


I believe you can't simply use arithmetic operator onto BigInteger object. Try to use their methods for arithmetic processes such as comparing, subtracting, multiplying etc.

References are given here



来源:https://stackoverflow.com/questions/10780209/difficulty-with-biginteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!