计算大数阶乘c语言,用C语言计算大数的阶乘

前两个月跟论坛上的laigaoat2005说了一道计算阶乘的题,那时随便写了下没写出合适的,就放在一边了。

昨天跟laigaoat2005聊天又谈到这个问题,决定重新写一下这个代码,于是就有了下面的代码。

在代码中我把内存申请系数设置为4,可以计算10000以内的阶乘,如果需要计算更大的数,则需要将该系数适当增大。刚才在自己的机子上测试计算100000的阶乘,结果因为计算量太大花的时间太长而中途手动中止,哪位朋友的机子性能好有兴趣的话可以算一下100000的阶乘。

不知道有没有高效的计算方法,我总觉得自己的算法效率不高,欢迎大家指点。

/* Factorial.c  — 计算大数的阶乘

* Author: Space

* Date:    2007/07/03

* Version: 1.0

*/

#include

#include  // for malloc()

#include  // for memset()

#define QUOTIETY  4  // 内存分配系数,计算10000以内阶乘设置为4就足够,如果需要

// 计算更大的数的阶乘,则将该系数适当增大

void process(const int index, int *result);

int cnt = 1;

int main(void)

{

int index = 0;

int input = 0;

int *result = NULL;

// 获得输入数据

printf(“请输入你要计算的阶乘数,内存有限,请不要超过10000:\n”);

scanf(“%d”, &input);

while (input <= 0 || input > 10000)

{

printf(“请输入合理的数据,谢谢:\n”);

scanf(“%d”, &input);

}

// 申请空间储存计算结果

result = (int *)malloc(sizeof(int) * input * QUOTIETY);

if (result == NULL)

{

printf(“内存申请失败!\n”);

exit(-1);

}

memset(result, 0, sizeof(int) * input * QUOTIETY);  // 初始化存储空间

result[0] = 1;

// 进行阶乘计算

for ( index = 1; index <= input; ++index)

{

process(index, result);

}

// 打印结果

for (index = cnt – 1; index >= 0L; –index)

{

printf(“%d”, result[index]);

}

putchar(‘\n’);

printf(“结果一共有%d位数!\n”, cnt);

free(result);

return 0;

}

/*

*  计算阶乘核心代码

*/

void process(const int index, int *result)

{

int product = 0;  // 乘积

int carry = 0;    // 进位

int remainder = 0;  // 余数

int i = 0;

for (i = 0; i < cnt; ++i)

{

product = result* index + carry;

carry = product / 10;

remainder = product % 10;

result= remainder;

}

if (carry != 0)

{

while (carry / 10 != 0)

{

result[cnt] = carry % 10;

carry /= 10;

++cnt;

}

result[cnt++] = carry;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值