use*_*693 2 java biginteger factorial
我试图用Recursion和BigIntegers做Factorial,但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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
NPE*_*NPE 10
BigInteger不支持比较使用==和乘法使用*.相反,您必须调用BigInteger类(equals()和multipy())的适当方法.
还要注意存在BigInteger.ZERO和BigInteger.ONE.
最后,您的方法的返回类型fact应该是,BigInteger而不是int.您是希望参数是类型BigInteger还是int由您决定.
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |