首页 > 代码库 > 例题2-3 阶乘之和

例题2-3 阶乘之和

题目要求:输入n,计算s = 1!+2!+3!+…n!的末6位,n<=10^6

样例输入:10

样例输出:37913

源代码:

 1 #include <stdio.h>
 2 #include <time.h>
 3 
 4 int main()
 5 {
 6     //const int MOD = 1000000;
 7     int i,j,n,s = 0;
 8     scanf("%d",&n);
 9     for (i = 1;i <= n;i++)
10     {
11         int factorial = 1;
12         for (j = 1;j <= i;j++)
13             factorial = (factorial * j );
14         s = (s + factorial);
15     }
16     printf("%d\n",s%1000000);
17     printf("Time = %.21f\n",(double)clock() / CLOCKS_PER_SEC);
18     return 0;
19 }

这是先求和再取模

如果逐步取模再求和的话,如下:

 1 #include <stdio.h>
 2 #include <time.h>
 3 
 4 int main()
 5 {
 6     const int MOD = 1000000;
 7     int i,j,n,s = 0;
 8     scanf("%d",&n);
 9     for (i = 1;i <= n;i++)
10     {
11         int factorial = 1;
12         for (j = 1;j <= i;j++)
13             factorial = (factorial * j %MOD);
14         s = (s + factorial)%MOD;
15     }
16     printf("%d\n",s);
17     printf("Time = %.21f\n",(double)clock() / CLOCKS_PER_SEC);
18     return 0;
19 }

第一段的话,小数字可以,输入100就乘法溢出了

第二段大数字也可以,就是数字过大程序跑得时间太长了;

例题2-3 阶乘之和