原创:大数阶乘的讨论(3)

上次,我使用了字符数组来实现了大数阶乘的高精度计算,但效率较低,现在我又使用了uint数组来代替char数组,这样的速度又快了很多,代码也得以大为简化,现贴c语言源码如下,gcc编译通过:

//: High Precision Calculator updated at 17:14 7/11/2007 By Lewis Cheng
//PS This program only support 40000(or below)!
#include <stdio.h>
#include <time.h>

#define MOD_LEN 5
#define MAX_COUNT 33343 // Effective length= MAX_COUNT*5
#define MODULE 100000

typedef unsigned int UINT;

UINT ARRAY[MAX_COUNT];
int COUNT;
int i;

void INIT()
{
     for(i=1;i<MAX_COUNT;i++) ARRAY[i]=0;
     ARRAY[0]=1;
     COUNT=1;
}

void PRINT()
{
     FILE *fp=fopen("fact.txt","w");
     for(i=COUNT-1;i>=0;i--)
     {
         fprintf(fp,"%.5d ",ARRAY[i]);
     }
     fclose(fp);
}

void MULTIPLY(UINT n)
{
     UINT R=0,T;
     for(i=0;i<=COUNT-1;i++)
     {
             T=ARRAY[i]*n+R;
             R=T/MODULE;
             ARRAY[i]=T%MODULE;
     }
     if(R!=0)
     {
        ARRAY[COUNT]=R;
        COUNT++;
     }
}

void FACT(int n)
{
     INIT(); 
     long t=clock();
     while(n>1)
     {
          MULTIPLY(n);
          n--;
     }
     t=clock()-t;
     PRINT();
     printf("time elapsed :%d ms/n",t);
}

void POWER(int x,int y)
{
     INIT();
     long t=clock();   
     while(y>1)
     {
          MULTIPLY(x);
          y--;    
     }  
     t=clock()-t;
     PRINT();
     printf("time elapsed :%d ms/n",t); 
}

int main()
{     
       int n;
  while(1)
  {
          printf("input a n[0-40000]:");
          scanf("%d",&n);
          FACT(n);
          printf("Open fact.txt to see the result!/n");
  }
  return 0;
}
它会把计算结果写入文件fact.txt里,本机测试10000!用了328ms,速度可快了很多哟!

但根据测试的n大小不同,需要修改mod_len和max_count!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值