[英]Why does my recursion program print a negative number?
My code for whatever reason is printing out a negative number when i run it with certain numbers(17). 我的代码无论出于什么原因都在我使用某些数字运行它时打印出一个负数(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);
}
}
You're encountering integer overflow. 您遇到整数溢出。
factorial(17) is 3.5568743e+14, which is well beyond the bounds of int
. factorial(17)是3.5568743e + 14,这远远超出了
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 [-2 63 , 2 63 -1] you can use long
instead of int
. 如果需要[-2 63,2 63 -1]范围内的整数,则可以使用
long
代替int
。 If you want arbitrarily large integers, use BigInteger
instead. 如果要任意大的整数,请改用
BigInteger
。 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));
}
Factorials grow quickly in value, such that 17! 阶乘的价值快速增长,例如17! (355687428096000) too large to fit in an
int
, causing overflow and the negative number. (355687428096000)太大,无法放入
int
,从而导致溢出和负数。
Return a long
from factorial
, so that when the multiplication occurs, it won't overflow (yet). 从
factorial
返回long
,以便在发生乘法运算时(不会)溢出。 You'll need to declare x
as a long
also. 您还需要将
x
声明为long
。 Note that this will only postpone the problem, because sufficiently high values of N
will overflow a long
too. 请注意,这只会推迟问题,因为足够高的
N
值也会long
溢出。 If necessary, use BigInteger
s. 如有必要,请使用
BigInteger
。
This is because the maximum value an int
can have is 2,147,483,647
. 这是因为
int
可以具有的2,147,483,647
为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
开始计数。
2,147,483,647 + 1 = -12,147,483,647
Try a long or BigDecimal
instead =) 尝试使用long或
BigDecimal
代替=)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.