用字符串实现的大数阶乘,未优化,仅供参考
程序代码:
#include<stdio.h> #define max_len 1024 int intpow(int n, int m) { int i,sum = 1; for(i = 0; i< m; i++) { sum = sum * n; } return sum; } int main() { char str[max_len],str_temp[max_len],str_copy[max_len];//str:阶乘值,str_copy:保存上次乘后的值,str_temp:临时变量 int i,j,val,n,len,len_temp,len_copy,carry,index; //carry:进位.index:指数 printf("输入一个整数:"); scanf("%d",&n); memset(str,0,sizeof(str)); memset(str_temp,0,sizeof(str_temp)); str[0]=1; len=1; for(i=1;i<=n;i++) { index=0; len_copy = len; memcpy(str_copy,str,max_len); memset(str,0,sizeof(str)); len = 0; while(i/intpow(10,index)>0) { memset(str_temp,0,sizeof(str_temp)); memcpy(str_temp+index,str_copy,len_copy); len_temp=len_copy+index; val=i/intpow(10,index)%10; carry=0; for(j=0;j<len_temp;j++) { str_temp[j]=str_temp[j]*val+carry; carry=str_temp[j]/10; str_temp[j]=str_temp[j]%10; } if(carry>0) { str_temp[len_temp]=carry; len_temp+=1; } for(j=0,carry=0;j<len_temp;j++) { str[j]=str_temp[j]+str[j]+carry; carry=str[j]/10; str[j]=str[j]%10; } if(carry>0) { str[len_temp]=carry; len=len_temp+1; } else { len=len_temp; } index++; } } printf("value="); for(j=len-1;j>=0;j--) { printf("%d",str[j]); } printf("\n"); return 0; }
一沙一世界,一花一天堂。无限掌中置,刹那成永恒。