问题描述
好的,所以我正在尝试解决这个问题:http://www.spoj.pl/问题/FCTRL2/
OK,so I am trying to solve this problem: http://www.spoj.pl/problems/FCTRL2/
利用我对 c 的了解,我想出了这个代码:
And using what I know about c, I have come up with this code:
#include <stdio.h>
#include <conio.h>
long double factorial(int);
int main()
{
long double num[100], fact[100];
int i = 0, ex;
scanf("%d", &ex);
for ( i = 0; i < ex; i++ )
{
scanf("%lf", &num[i]);
}
i = 0;
printf("\n");
for (i = 0; i < ex; i++ )
{
fact[i] = factorial(num[i]);
printf("%.0lf\n", fact[i]);
}
getch();
return 0;
}
long double factorial(int num)
{
long double onum, fact;
int i;
fact = 1;
onum = num;
for ( i = 1; i < onum; i++ )
{
fact = fact * num;
num--;
}
return fact;
}
问题在于 long double 的长度不足以容纳 100 之久的值!那么,我如何创建一个可以保存这么大值的数据类型?
The problem is that long double is not long enough to hold values as long as 100! So, how can I create a datatype that can hold this large value?
推荐答案
对于这个特定的问题,GMP 确实是一种矫枉过正.
For this particular problem, GMP is indeed an overkill.
事实上,即使是 Carl Norum 提出的结构,虽然有用且更通用,但包含的内容超出了您的需要.特别是,由于所有阶乘都是正整数,因此您无需担心符号.
In fact, even the struct presented by Carl Norum, while useful and more general, contains more than what you will need. In particular, since all factorials are positive integers you don't need to worry about the sign.
此外,没有必要实现加法、减法,甚至一般的乘法.您只需要担心将这些大数"中的一个乘以一个整数,这并不难.
Also, it's not necessary to implement addition, subtraction, or even general multiplication. You only need to worry about multiplying one of these "bignums" by an integer, which isn't too hard.
这是乘法运算的存根
void multiply( mybignum bn, int factor ) {
// for each of the digits in 'bn'
// multiplies 'factor' by the particular digit
// adds the previous remainder and stores
// the new carry value
}
这篇关于如何在 C 中创建一个数据类型来保存 200+ 位长数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!