无法计算大于20的阶乘!!怎么办?

Ves*_*nog 13 c gcc factorial

我使用无符号长整数格式来计算大因子.但是我的代码在某些时候失败了你能看一下吗?实际上它是指数函数的泰勒展开的更大代码的一部分,但是这一部分在这一点上是无关紧要的.我将不胜感激任何建议.

谢谢

#include <stdio.h>
#include <math.h>
//We need to write a factorial function beforehand, since we
//have factorial in the denominators.
//Remembering that factorials are defined for integers; it is
//possible to define factorials of non-integer numbers using
//Gamma Function but we will omit that.
//We first declare the factorial function as follows:
unsigned long long factorial (int);
//Long long integer format only allows numbers in the order of 10^18 so 
//we shall use the sign bit in order to increase our range.
//Now we define it,
unsigned long long
factorial(int n)
{
//Here s is the free parameter which is increased by one in each step and
//pro is the initial product and by setting pro to be 0 we also cover the
//case of zero factorial.
    int s = 1;
    unsigned long long pro = 1;
    if (n < 0)
        printf("Factorial is not defined for a negative number \n");
    else {
    while (n >= s) { 
    printf("%d \n", s);
    pro *= s;
    s++;
    printf("%llu \n", pro);
    }
    return pro;
    }
}

int main ()
{
    int x[12] = { 1, 5, 10, 15, 20, 100, -1, -5, -10, -20, -50, -100};
//Here an array named "calc" is defined to store 
//the values of x.
unsigned long long  k = factorial(25);
printf("%llu \n", k);

//int k;
////The upper index controls the accuracy of the Taylor Series, so
////it is suitable to make it an adjustable parameter. 
//int p = 500;
//for ( k = 0; k < p; k++);

}
Run Code Online (Sandbox Code Playgroud)

ari*_*ing 15

无符号多头的限制是18446744073709551615,或约1.8e + 19.20!约为2.4e + 18,因此在范围内,不过21!大约是5.1e + 19,超过了无符号长长的最大大小.

您可能会发现这有用:C++中是否存在大于long long int的类型?


Bil*_*nch 7

你的整数类型溢出了.这可能unsigned long long是64位长.

  • 20!是0x21c3_677c_82b4_0000哪个适合.
  • 21!是0x2_c507_7d36_b8c4_0000不适合.

您可以查看像GMP这样的库,它可以实现任意大整数.


扩展GMP评论.以下是一些使用GMP计算阶乘的代码:

void factorial(unsigned long long n, mpz_t result) {
    mpz_set_ui(result, 1);

    while (n > 1) {
        mpz_mul_ui(result, result, n);
        n = n-1;
    }
}

int main() {
    mpz_t fact;
    mpz_init(fact);

    factorial(100, fact);

    char *as_str = mpz_get_str(NULL, 16, fact);
    printf("%s\n", as_str);

    mpz_clear(fact);
    free(as_str);
}
Run Code Online (Sandbox Code Playgroud)

这将计算factorial(100),并导致:

0x1b30964ec395dc24069528d54bbda40d16e966ef9a70eb21b5b2943a321cdf10391745570cca9420c6ecb3b72ed2ee8b02ea2735c61a000000000000000000000000
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,这是C++版本.构造函数,析构函数和运算符重载往往使这些东西的C++版本看起来更清晰.结果与以前相同.

#include <gmpxx.h>
#include <iostream>

int main() {
    mpz_class fact = 1;

    for (int i=2; i<=100; ++i)
        fact *= i;

    std::cout << "0x" << fact.get_str(16) << "\n";
}
Run Code Online (Sandbox Code Playgroud)


hac*_*cks 5

范围unsigned long long通常为02 ^ 64 - 1(18,446,744,073,709,551,615).21!超出这个范围.