BigInteger难度大 [英] Difficulty with BigInteger
问题描述
我正在尝试使用Recursion和BigIntegers进行Factorial,但eclipse正在抱怨BigInteger。我知道这个程序本来应该很简单,但它给我带来了麻烦。这是代码。
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);
}
}
}
推荐答案
BigInteger
不支持使用 ==
进行比较,并使用进行乘法*
。相反,您必须调用 BigInteger
类的相应方法( equals()
和 multipy()
)。
BigInteger
does not support comparison using ==
and multiplication using *
. Instead, you have to call the appropriate methods of the BigInteger
class (equals()
and multipy()
).
另请注意,存在 BigInteger.ZERO
和 BigInteger.ONE
。
Also note that there exist BigInteger.ZERO
and BigInteger.ONE
.
最后, fact
方法的返回类型应该是 BigInteger
而不是 INT
。是否希望参数的类型为 BigInteger
或 int
由您决定。
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.
这篇关于BigInteger难度大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!