递归阶乘方法返回一些负数 [英] Recursive factorial method returning some negative numbers

查看:133
本文介绍了递归阶乘方法返回一些负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的析因方法:

public static long factorial(int num1) {
    if (num1 <= 1) 
        return 1; 
    else
        return num1 * factorial(num1 - 1);
}

这就是所谓的递归阶乘方法:

And this is what calls this recursive factorial method:

for (i = 0; i <= 25; i++)
    System.out.printf  ("%d !=  %,d\n", i, factorial (i));

到目前为止,到目前为止,输出看起来似乎是正确的,但是某些阶乘是负数而不是正数:

So far so good, the output seems correct at first but some factorials are negative instead of positive:

OUTPUT:
0 !=  1
1 !=  1
2 !=  2
3 !=  6
4 !=  24
5 !=  120
6 !=  720
7 !=  5,040
8 !=  40,320
9 !=  362,880
10 !=  3,628,800
11 !=  39,916,800
12 !=  479,001,600
13 !=  6,227,020,800
14 !=  87,178,291,200
15 !=  1,307,674,368,000
16 !=  20,922,789,888,000
17 !=  355,687,428,096,000
18 !=  6,402,373,705,728,000
19 !=  121,645,100,408,832,000
20 !=  2,432,902,008,176,640,000
21 !=  -4,249,290,049,419,214,848
22 !=  -1,250,660,718,674,968,576
23 !=  8,128,291,617,894,825,984
24 !=  -7,835,185,981,329,244,160
25 !=  7,034,535,277,573,963,776

21、22和24是负面的,为什么会这样?这是某种被0除"的悖论吗?

21, 22 and 24 are negative, why is this happening? Is this some kind of "divide by 0" paradox?

推荐答案

您正在长篇大论.您需要根据包含长值的二进制数来考虑它.在long可以包含的最大正值上加上1后,它就会滚动到负的最小值.

You are overflowing the long. You need to think of it in terms of the binary number that contains the long value. As soon as you add 1 to the maximum positive value that the long can contain, it rolls to the negative minimum.

您可能需要阅读此书以获得完整的理解. http://en.wikipedia.org/wiki/Two%27s_complement

You might want to read this for a full understanding. http://en.wikipedia.org/wiki/Two%27s_complement

在Java中,您可以使用BigInteger获得更大的值 http://docs.oracle.com/javase /1.4.2/docs/api/java/math/BigInteger.html

In Java you can use BigInteger for bigger values http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html

这篇关于递归阶乘方法返回一些负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆