HDU 1042 N!(高精度计算阶乘)

时间:2023-03-09 09:33:04
HDU 1042 N!(高精度计算阶乘)

N!

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34687    Accepted Submission(s): 9711

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
思路分析:简单的高精度算法。
  1.基本思想:
  把运算结果倒着保存在一个大数组f中。
  每次循环更新每一位*(当前的操作数i)+进位c.并处理超过当前数字长度的进位c。更新数字长度。
  最后,找到不为零的数组位置,开始倒着输出即可。
 #include<cstdlib>
#include<cstdio>
#include<string.h>
#define MAX 10000
int f[MAX];
int main()
{
int n;//阶乘数
while (scanf("%d",&n)!=EOF)
{
memset(f,,sizeof(f));//清空运算数组
f[]=;
int i,j,count=;//数的总位数,进位时+1
for (i = ; i <=n; i++)//<=n的数循环高精度
{
int c=;//进位
for (j = ; j < count; j++)
{
int ans=f[j]*i+c;
f[j]=ans%;//所在位取余数
c=ans/;
}
while (c)//进位
{
f[count++]=c%;
c/=;
}
}
int k=MAX-;
while (!f[k])k--;//找到数组结果不为零的开始.
for (i = k; i >= ; i--)
printf("%d",f[i]);
printf("\n");
}
return ;
}