Linux中国 Linux中国门户站!
设为主页 设为主页
收藏本站 收藏本站
 
当前位置 :首页 ->编程语言 ->C/C++ ->正文

阶乘计算器改进版

来源: 作者: 时间:2007-04-12 点击: [收藏] [投稿]
帖及讨论:http://bbs.bc-cn.net/dispbbs.asp?BoardID=5&ID=118393

只要你有内存和空间,该程序可无限扩展
默认设置最大计算100000!可精确到每一位
这是以前我做的程序的改进版,速度提升了1/3


/*SK-CHINA 阶乘计算器*/
/*本程序可以准确计算十万以内的阶乘*/
/*结果输出为out.txt*/
#include "stdio.h"
long s[500000]={0L}; /*存储数据*/
long h=499999L; /*数据位置*/
int cheng(long num) {
    long t=499999L;
    while(s[h]==0) h++;
    if(num>=100000L) h--;
    if(num>=10000L) h--;
    if(num>=1000L) h--;
    if(num>=100L) h--;
    if(num>=10L) h--;
    h--;
    while(t!=h) {
      s[t]=s[t]*num;
      t--;
    } t=499999L;
    h=h-5L;
    while(t!=h) {
      s[t-1]+=s[t]/10;
      s[t]=s[t]%10;
      t--;
    }
    h=h+5L;
}
int main(void) {
    int i;
    long x;
    FILE *output;
    s[499999]=1L;
    output=fopen("out.txt","w");
    scanf("%ld",&x); /*输入数据*/
    for(i=1;i<=x;i++) cheng(i);
    for(i=0;i<500000L;i++) {
      if(i%500==0) fprintf(output,"\n");
      fprintf(output,"%ld",s[i]);
    }
    return 0;
}

完整版:
速度较上面的稍慢,但较为友好
/*SK-CHINA 阶乘计算器*/
/*本程序可以准确计算十万以内的阶乘*/
/*结果输出为out.txt*/
#include "stdio.h"
long s[500000]={0L}; /*存储数据*/
long h=499999L; /*数据位置*/
int cheng(long num) {
    long t=499999L;
    while(s[h]==0) h++;
    if(num>=100000L) h--;
    if(num>=10000L) h--;
    if(num>=1000L) h--;
    if(num>=100L) h--;
    if(num>=10L) h--;
    h--;
    while(t!=h) {
      s[t]=s[t]*num;
      t--;
    } t=499999L;
    h=h-5L;
    while(t!=h) {
      s[t-1]+=s[t]/10;
      s[t]=s[t]%10;
      t--;
    }
    h=h+5L;
}
int main(void) {
    int i;
    long x;
    FILE *output;
    s[499999]=1L;
    output=fopen("out.txt","w");
    printf("SK-CHINA 阶乘计算器\n请输入数据:");
    scanf("%ld",&x); /*输入数据*/
    for(i=1;i<=x;i++) { cheng(i); printf("\r当前已计算至%ld!",i); }
    printf("\n计算结束,现在程序正在把结果保存到out.txt\n");
    for(i=0;i<500000L;i++) {
      if(i%500==0) fprintf(output,"\n");
      fprintf(output,"%ld",s[i]);
    }
    printf("写入结束!按任意键退出");
    getch();
    return 0;



 如果您对本文有任何疑问或者建议,请到讨论区发表您的意见: >> 论坛入口 <<



上一篇:C语言图形模式编程,个性鼠标   下一篇:C语言教程第九章:预处理

文章评论】 【收藏本文】 【推荐好友】 【打印本文】 【我要投稿】 【论坛讨论
更多相关文章
Power by linux-cn.com 粤ICP备05006655号