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

来源:互联网 发布:钢铁侠玩具模型淘宝 编辑:程序博客网 时间:2024/04/28 01:40

上次,我使用了字符数组来实现了大数阶乘的高精度计算,但效率较低,现在我又使用了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!

原创粉丝点击