输入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;
}