简体   繁体   English

递归因子函数无法正常工作

[英]Recursive factorial function not working properly

Why this recursive function can only calculate up to (20!) ? 为什么这个递归函数最多只能计算(20!)? When I input 21 it shows unexpected result. 当我输入21时,它显示意外的结果。

#include <iostream>
using namespace std;

long long int factorial( long long int number )
{
    if( number <= 1 )
        return 1;

    return number * factorial( number - 1 );

} }

int main()
{
    long long int number;
    while( cin >> number )
            cout << factorial( number ) << endl; // factorial( 20 ) = 2432902008176640000
                                                 // factorial( 21 ) = -4249290049419214848 ????
    return 0;
}

The factorial of 21 is 51090942171709440000 . 阶乘21是51090942171709440000 A signed long long on your computer can hold has a maximum of 2^63-1 = 9223372036854775807 . 您的计算机上可以保存的签名长的最长为2^63-1 = 9223372036854775807

2432902008176640000    20 factorial
9223372036854775807    2^63-1 (the maximum for a long long on your computer)
51090942171709440000   21 factorial

When a number is larger than the maximum then behavior is undefined. 当数字大于最大值时,行为未定义。 What happens on most computers is that it wraps around to the most negative number. 大多数计算机上发生的事情是它包含最负数。


Because integral type long long has its maximum that it can store. 因为整数型long long有它可以存储的最大值。 You can get it using the following statement 您可以使用以下语句获取它

#include <iostream>
#include <limits>

int main()
{
    std::cout << std::numeric_limits<long long>::max() << std::endl;
}

Here are factorials for type long long provided that it occupies 8 bytes. 这里是long long类型的阶乘,只要它占用8个字节。

 0: 1 
 1: 1 
 2: 2 
 3: 6 
 4: 24 
 5: 120 
 6: 720 
 7: 5040 
 8: 40320 
 9: 362880 
 10: 3628800 
 11: 39916800 
 12: 479001600 
 13: 6227020800 
 14: 87178291200 
 15: 1307674368000 
 16: 20922789888000 
 17: 355687428096000 
 18: 6402373705728000 
 19: 121645100408832000 
 20: 2432902008176640000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM