hdu1042N!(大数)

来源:互联网 发布:西方建筑欣赏知乎 编辑:程序博客网 时间:2024/06/06 15:23

N!

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 262144/262144K (Java/Other)
Total Submission(s) : 2   Accepted Submission(s) : 1
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
123
 

Sample Output
126
 此题为大数的阶乘,主要方法就是用数组来不断存储计算好的阶乘,若i=1、2、3、4.......n;每次乘 i 都相当于模拟我们平常计算两个数相乘,直到乘到n.代码如下:
#include<stdio.h>#include<string.h>#define MAX 36010int a[MAX];             //定义一个数组用来存储不断更新的阶乘的各位数;int main(){int n;int i,j,k,s;while(scanf("%d",&n)!=EOF){memset(a,0,sizeof(a));a[0]=1;k=0;for(i=2;i<=n;i++)     //用来从2到n;{for(j=0;j<=MAX;j++){s=a[j]*i+k;    //计算i与当前数的各位数相乘并加上进位的数K;a[j]=s%10;     //将当前的阶乘的各位数字依次存到数组a中;
k=s/10;        //去除末尾的数;}}for(i=MAX;i>=0;i--) if(a[i]>0)  break;for(j=i;j>=0;j--) printf("%d",a[j]);printf("\n");}return 0;}


0 0
原创粉丝点击