阶乘之和

输入n,计算S=1!+2!+3!+...+n!的末6位(不含前导0)。n<=1000000。这里,n!表示前n个正整数之积。

样例输入:10

样例输出:37913

#include<stdio.h>
#include<time.h>
int main(){
	const int MOD=1000000;
	int n,i,j;
	freopen("a.txt","r",stdin);
	freopen("b.txt","w",stdout);
	while(scanf("%d",&n)==1){
		int sum=0;
		for(i=1;i<=n;i++){
			int factorial=1;
			for(j=1;j<=i;j++)
				factorial=factorial*j%MOD;
			sum=(sum+factorial)%MOD;
		}
		printf("%d\n",sum);
		printf("The time used:%.2lf\n",(double)clock()/CLOCKS_PER_SEC);
	}
	return 0;
}

测试:

输入:

20
21
22
23
24
25
40
80
160
1600
6400
12800
25600
51200

输出:

820313
The time used:0.00
260313
The time used:0.00
940313
The time used:0.00
580313
The time used:0.00
940313
The time used:0.00
940313
The time used:0.00
940313
The time used:0.00
940313
The time used:0.00
940313
The time used:0.00
940313
The time used:0.01
940313
The time used:0.22
940313
The time used:1.02
940313
The time used:4.20
940313
The time used:16.87

当n=25!末六位均为0,故第25项后,结果一样,于是有

#include<stdio.h>
int main(){
	const int MOD=1000000;
	int factorial=1,n,a[26];
	a[0]=0;
	for(int i=1;i<=25;i++){
		factorial=(factorial*i)%MOD;
		a[i]=(a[i-1]+factorial)%MOD;
	}
	//freopen("a.txt","r",stdin);
	//freopen("b.txt","w",stdout);
	while(scanf("%d",&n)==1){
		if(n<25)
			printf("%d\n",a[n]);
		else
			printf("%d\n",a[25]);
			
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值