杭电HDU 1042大数阶乘N!
发布时间:2020-12-14 02:26:40 所属栏目:大数据 来源:网络整理
导读:Problem Description Given an integer N(0 ≤ N ≤ 10000),your task is to calculate N! ? Input One N in one line,process to the end of file. ? Output For each N,output N! in one line. ? Sample Input 1 2 3 ? Sample Output 1 2 6 效率较高的代码
Problem Description
Given an integer N(0 ≤ N ≤ 10000),your task is to calculate N! ? Input One N in one line,process to the end of file. ? Output For each N,output N! in one line. ? Sample Input 1 2 3 ? Sample Output 1 2 6 效率较高的代码:
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #define MAXN 10000+5 int main() { int f[MAXN],c=0,n,len; while(scanf("%d",&n)!=EOF) { memset(f,sizeof(f)); f[0]=1; len=0; for(int i=2;i<=n;i++) //阶乘乘的数 { c=0; //进位 for(int j=0;j<=len;j++) //被乘数的每一位都要乘乘数 { f[j]=f[j]*i+c; c=f[j]/10000; f[j]%=10000; } if(c!=0) f[++len]=c; //这里是前置运算符,若写成len++结果会出错 } printf("%d",f[len]); //把最高位没有凑够四位的输出,防止有前导0 for(int i=len-1;i>=0;i--) printf("%04d",f[i]); //四位四位输出,不够的位数补0 printf("n"); } return 0; }
#include<stdio.h> #include<string.h> #define MAXN 40000+5 int f[MAXN]; int main() { int i,j,c,s; memset(f,sizeof(f)); while(scanf("%d",&n)!=EOF) { f[0]=1; for(i=2;i<=n;i++) { c=0; for(j=0;j<MAXN;j++) { s=f[j]*i+c; f[j]=s%10; c=s/10; } } for(i=MAXN-1;i>=0;i--) if(f[i]) break; for(j=i;j>=0;j--) printf("%d",f[j]); printf("n"); } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |