51nod 1057 n的阶乘 (压位优化)

题目地址:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1057&judgeId=605203

 

使用压位进行优化,即一位数存多位数,例如当设置MOD=1e8时,一位数可以存8位数;

其次,注意尾数0,因为压位,一位需要输出8个0,故第一个数应单独输出;

这样优化可以到100ms以内;

 

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio> 
 4 using namespace std;
 5 
 6 #define min(a,b) a>b?b:a
 7 #define LL long long 
 8 const LL MOD = 1e8;
 9 const int N = 10000;
10 LL n, a[N];
11 
12 int main()
13 {
14     while(~scanf("%lld", &n))
15     {
16         memset(a, 0, sizeof(a));
17         a[0]=1;
18         
19         int len=0, carry=0;
20         for(int i=2; i<=n; i++) {
21             carry=0;
22             for(int j=0; j<=len; j++) {
23                 a[j] = a[j]*i+carry;
24                 carry = a[j]/MOD;
25                 a[j] %= MOD;
26             }
27             if(carry>0) {
28                 a[++len]=carry;
29             }
30         }
31         printf("%lld", a[len--]);
32         while(len>=0) {
33             printf("%0.8lld", a[len]);
34             len--;
35         }
36         putchar('\n');
37     }
38     return 0;
39 }

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值