无法计算大于 20 的阶乘!!怎么做? [英] Cannot calculate factorials bigger than 20! ! How to do so?

查看:22
本文介绍了无法计算大于 20 的阶乘!!怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using unsigned long long integer format in order to calculate big factorials. However my code fails at some point can you have a look at it? Actually it is part of a larger code for Taylor expansion of exponential function, but that part is irrelevant at this point. I will appreciate any suggestions.

谢谢

#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 
");
    else {
    while (n >= s) { 
    printf("%d 
", s);
    pro *= s;
    s++;
    printf("%llu 
", 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 
", 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++);

}

推荐答案

unsigned long long 的限制是 18446744073709551615,大约是 1.8e+19.20!大约是 2.4e+18,所以在范围内,但是 21!大约是 5.1e+19,超过了一个 unsigned long long 的最大长度.

The limit on an unsigned long long is 18446744073709551615, or about 1.8e+19. 20! is about 2.4e+18, so within range, however 21! is about 5.1e+19, exceeding the maximum size of an unsigned long long.

您可能会发现这很有帮助:是否有比 long long int 更大的类型C++?

You may find this helpful: Are there types bigger than long long int in C++?

这篇关于无法计算大于 20 的阶乘!!怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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