《算法竞赛入门经典》第二章 2.2

程序2-4

 1 #include<stdio.h>

 2 #include<math.h>

 3 int main()

 4 {

 5     int n, count = 0;

 6     scanf("%d",&n);

 7     while(n>1)

 8     {

 9         if(n % 2 ==1) n = 3*n +1;

10         else n/=2;

11         count++;

12     }

13     printf("%d\n",count);

14     return 0;

15 }

程序2-5

 1 #include<stdio.h>

 2 #include<math.h>

 3 int main()

 4 {

 5     int i, j, n, S = 0;

 6     scanf("%d",&n);

 7     for(i = 1;i<=n;i++)

 8     {

 9         int factorial = 1;

10         for(j = 1;j <=i;j++)

11         {

12             factorial *= j;

13         }

14         S +=factorial;

15     }

16     printf("%d\n",S % 1000000);

17     return 0;

18 }

 程序2-6

 1 #include<stdio.h>

 2 #include<time.h>

 3 int main()

 4 {

 5     const int MOD = 1000000;

 6     int i, j, n, S = 0;

 7     scanf("%d",&n);

 8     for(i = 1;i<=n;i++)

 9     {

10         int factorial = 1;

11         for(j = 1;j <=i;j++)

12         {

13             factorial = (factorial*j%MOD);

14         }

15         S = (S+factorial)%MOD;

16     }

17     printf("%d\n",S);

18     printf("Time used = %0.2lf\n",(double)clock() /CLOCKS_PER_SEC);

19     return 0;

20 }

 

你可能感兴趣的:(算法)