我使用无符号长整数格式来计算大阶乘。但是我的代码在某个时候失败了,你能看看吗?实际上,它是指数函数泰勒展开的一个大码的一部分,但这一部分在这一点上是无关的。如有任何建议,我将不胜感激。
谢谢
#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++);
}
最佳答案
无符号长的限制是18446744073709551615,即大约1.8e+19。20岁!大约是2.4e+18,所以在范围内,但是21!约为5.1e + 19,超过未签名长长的最大大小。
您可能会发现这很有帮助:Are there types bigger than long long int in C++?
关于c - 无法计算大于20的阶乘! !怎么做?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19230573/