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

本文介绍了一个使用C语言实现的大整数阶乘(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。更新数字长度
  最后,找到不为零的数组位置,开始倒着输出即可。
 1 #include<cstdlib>
 2 #include<cstdio>
 3 #include<string.h>
 4 #define MAX 10000
 5 int    f[MAX]; 
 6 int main()
 7 {
 8     int n;//阶乘数
 9     while (scanf("%d",&n)!=EOF)
10     {
11         memset(f,0,sizeof(f));//清空运算数组
12         f[0]=1;
13         int i,j,count=1;//数的总位数,进位时+1
14         for (i = 2; i <=n; i++)//<=n的数循环高精度
15         {
16             int c=0;//进位
17             for (j = 0; j < count; j++)
18             {
19                 int ans=f[j]*i+c;
20                 f[j]=ans%10;//所在位取余数
21                 c=ans/10;
22             }
23             while (c)//进位
24             {
25                 f[count++]=c%10;
26                 c/=10;
27             }
28         }
29         int k=MAX-1;
30         while (!f[k])k--;//找到数组结果不为零的开始.
31         for (i = k; i >=0 ; i--)
32             printf("%d",f[i]);
33         printf("\n");
34     }
35     return 0;
36 }

 

转载于:https://www.cnblogs.com/renhongleiz/p/renhongleiz.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值