java 中出现 BigInteger 的 StackOverFlowError
StackOverFlowError with BigInteger in java
为什么这个 java 代码抛出 WhosebugError
异常?
public class factorial2 {
public BigInteger fact( BigInteger n)
{
BigInteger one = new BigInteger("1");
if(n.equals("0"))
return one;
else
return n.multiply(fact(n.subtract(one)));
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
factorial2 f = new factorial2();
for(int i=0;i<n;i++)
{
BigInteger b = sc.nextBigInteger();
System.out.println(f.fact(b));
}
sc.close();
}
}
我尝试使用 BigInteger
生成阶乘。但是,为什么我的代码在输入时给出引用异常?
BigInteger#equals 方法
public boolean equals(Object x) {
// This test is just an optimization, which may or may not help
if (x == this)
return true;
if (!(x instanceof BigInteger))
return false;
此条件始终为假
if (n.equals("0"))
改为使用
if (BigInteger.ZERO.equals(n))
问题出在你的基本案例上; n
(BigInteger
)不等于"0"
(String
)。因此,您继续执行 else
块,该块会再次出现。此外,BigInteger
包含 ONE
和 ZERO
的常量,因此您可以编写类似
的内容
public static BigInteger fact(BigInteger n) {
if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE))
return BigInteger.ONE;
else
return n.multiply(fact(n.subtract(BigInteger.ONE)));
}
或 使用一个三元运算(条件运算符? :
)像
public static BigInteger fact(BigInteger n) {
return (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) ? BigInteger.ONE
: n.multiply(fact(n.subtract(BigInteger.ONE)));
}
为什么这个 java 代码抛出 WhosebugError
异常?
public class factorial2 {
public BigInteger fact( BigInteger n)
{
BigInteger one = new BigInteger("1");
if(n.equals("0"))
return one;
else
return n.multiply(fact(n.subtract(one)));
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
factorial2 f = new factorial2();
for(int i=0;i<n;i++)
{
BigInteger b = sc.nextBigInteger();
System.out.println(f.fact(b));
}
sc.close();
}
}
我尝试使用 BigInteger
生成阶乘。但是,为什么我的代码在输入时给出引用异常?
BigInteger#equals 方法
public boolean equals(Object x) {
// This test is just an optimization, which may or may not help
if (x == this)
return true;
if (!(x instanceof BigInteger))
return false;
此条件始终为假
if (n.equals("0"))
改为使用
if (BigInteger.ZERO.equals(n))
问题出在你的基本案例上; n
(BigInteger
)不等于"0"
(String
)。因此,您继续执行 else
块,该块会再次出现。此外,BigInteger
包含 ONE
和 ZERO
的常量,因此您可以编写类似
public static BigInteger fact(BigInteger n) {
if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE))
return BigInteger.ONE;
else
return n.multiply(fact(n.subtract(BigInteger.ONE)));
}
或 使用一个三元运算(条件运算符? :
)像
public static BigInteger fact(BigInteger n) {
return (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) ? BigInteger.ONE
: n.multiply(fact(n.subtract(BigInteger.ONE)));
}