Why does my recursion program print a negative number?

不问归期 提交于 2019-12-08 15:21:25

问题


My code for whatever reason is printing out a negative number when i run it with certain numbers(17). It is supposed to find the factorial of a number and print it out however clearly that isn't happening.

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

回答1:


You're encountering integer overflow.

factorial(17) is 3.5568743e+14, which is well beyond the bounds of int. When an integer operation overflows, it can end up negative. For example:

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

In your case, you'll have overflowed several times - even if the result were positive, it still wouldn't be right.

If you need integers in the range of [-263, 263-1] you can use long instead of int. If you want arbitrarily large integers, use BigInteger instead. For example:

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



回答2:


Factorials grow quickly in value, such that 17! (355687428096000) too large to fit in an int, causing overflow and the negative number.

Return a long from factorial, so that when the multiplication occurs, it won't overflow (yet). You'll need to declare x as a long also. Note that this will only postpone the problem, because sufficiently high values of N will overflow a long too. If necessary, use BigIntegers.




回答3:


This is because the maximum value an int can have is 2,147,483,647. 17! exceeds this number. If an integer is assigned a number bigger than its maximum size, it starts counting up from -2,147,483,647.

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

Try a long or BigDecimal instead =)



来源:https://stackoverflow.com/questions/31144719/why-does-my-recursion-program-print-a-negative-number

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