计算大数阶乘C语言 [英] Calculating factorial of large numbers in C
问题描述
在我的C code,我要计算范围内的阶乘的数字1到100的小数字,该函数的作品,但对于例如100大的数字!它返回不正确的结果。任何方式来处理大量的阶乘C语言?使用编译器IM是gcc V4.3.3。 我的code是如下:
的#include< stdio.h中>
#包括<文件math.h>
双print_solution(INT);
INT主要(无效)
{
诠释no_of_inputs,N;
INT CTR = 1;
scanf函数(%d个,和放大器; no_of_inputs); //读取没有投入
做
{
scanf函数(%d个,和放大器; N); //读取输入
的printf(%0F \ N,print_solution(N));
CTR ++;
}而(CTR< = no_of_inputs);
返回0;
}
双print_solution(INT N)
{
如果(N == 0 ||ñ== 1)
返回1;
其他
返回N * print_solution(N-1);
}
没有标准的C数据类型将精确地处理数字大到100!如果使用任意precision整数运算,无论是通过库或你唯一的选择自己做的。
如果这只是一些业余爱好项目,我建议你自己想吧。这是一种有趣的运动。如果这是与工作有关的,使用pre-现有的库。
通常你将会得到最大的C数据类型为64位整数。 100!在10的顺序 157 ,这需要500位的大部分时间准确地存储为一个整数。
In my C code , i want to calculate the factorial for numbers in the range 1 to 100. For small numbers, the function works but for bigger numbers for example 100! it returns incorrect result. Any ways to handle factorial of large numbers in C ?. The compiler im using is gcc v4.3.3 . My code is as follows :
#include <stdio.h>
#include <math.h>
double print_solution(int);
int main(void)
{
int no_of_inputs,n ;
int ctr = 1;
scanf("%d",&no_of_inputs); //Read no of inputs
do
{
scanf("%d",&n); //Read the input
printf("%.0f\n",print_solution(n));
ctr++;
}while(ctr <= no_of_inputs);
return 0;
}
double print_solution(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n*print_solution(n-1);
}
No standard C data type will accurately handle numbers as large as 100!. Your only option if to use arbitrary precision integer arithmetic, either through a library or done by yourself.
If this is just some hobby project, I'd suggest trying it yourself. It's kind of a fun exercise. If this is work-related, use a pre-existing library.
The largest C data type you'll normally get is a 64 bit integer. 100! is in the order of 10157, which takes the better part of 500 bits to store accurately as an integer.
这篇关于计算大数阶乘C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!