为什么我的递归程序会打印一个负数?

时间:2015-06-30 17:34:05

标签: java eclipse recursion factorial

我的代码无论出于何种原因,当我使用某些数字运行它时会打印出一个负数(17)。它应该找到一个数字的阶乘,然后清楚地将其打印出来并且不会发生。

package recursion;

public class recursion_1 {

public static void main(String[] args) {
int x = factorial(17);
System.out.println(x);
}
public static int factorial(int N) { 
       if (N == 1) return 1; 
       return N * factorial(N-1); 
    }   
}

3 个答案:

答案 0 :(得分:2)

您遇到整数溢出。

factorial(17)是3.5568743e + 14,远远超出int的范围。当整数运算溢出时,它可能最终为负数。例如:

int x = Integer.MAX_VALUE;
x++;
System.out.println(x); // Very large negative number

在你的情况下,你会多次溢出 - 即使结果是积极的,它仍然不会正确

如果需要[-2 63 ,2 63 -1]范围内的整数,可以使用long代替int 。如果您想要任意大整数,请改用BigInteger。例如:

// Note rename of parameter to follow Java conventions
public static BigInteger factorial(int n) {
    return factorial(BigInteger.valueOf(n));
}

public static BigInteger factorial(BigInteger n) {
    if (n.equals(BigInteger.ONE)) {
        return BigInteger.ONE;
    }
    return n.multiply(n.subtract(BigInteger.ONE));
}

答案 1 :(得分:1)

因素在价值上迅速增长,这样17! (355687428096000)太大而无法容纳int,导致溢出和负数。

long返回factorial,这样当乘法发生时,它不会溢出(还)。您还需要将x声明为long。请注意,这只会推迟问题,因为N的足够高的值也会溢出long。如有必要,请使用BigInteger s。

答案 2 :(得分:0)

这是因为int可以拥有的最大值是2,147,483,64717!超过此数字。如果为整数分配的数字大于其最大大小,则会从-2,147,483,647开始向上计数。

2,147,483,647 + 1 = -12,147,483,647

尝试长或BigDecimal代替=)

相关问题