Example 2-4 The sum of factorial
Enter n, calculate s = 1! + 2! +3! +......+ n! The last 6 bits (excluding the leading 0). N <= 10^6,n! Represents the product of the first n positive integers.
Sample input:
10
Sample output:
37913
Program 2-7 factorial sum (1)
#include <stdio.h>intMain () {intN; scanf ("%d", &N); intsum =0; inti =1; while(I <=N) {//factorial saving the factorial value of I intfactorial =1; intj =1; for(J; J <= I; j + +) Factorial*=J; Sum+=factorial; I++; } printf ("%d\n", Sum%1000000); return 0;}
Input 10, perfect output.
Continue entering 100, output negative. It's obvious that multiplication has spilled again. The middle sum value is output by means of the output intermediate variable.
Can be found plus 13! The sum then overflowed. So what? Would it be possible to change int to the previous long long? Like Blake obviously due to the exponential increase in factorial, the role of modification is a drop in the bucket.
So what? Re-examining found that the output is the number of the last 6 bits. That is, the factorial and sum will be taken once each time to get the remainder operation. Overflow problem is solved by the knife, after all, the addition and multiplication, and will not change the results. Modify the program and add the timer function:
Program 2-8 factorial sum (2)
#include <stdio.h>#include<time.h>intMain () {intN; scanf ("%d", &N); intsum =0; inti =1; while(I <=N) {intfactorial =1; intj =1; for(J; J <= I; j + +) //take the last six bits to the factorialfactorial = factorial * J%1000000; Sum+=factorial; //take the last six bits to sumsum = sum%1000000; I++; } printf ("%d\n", sum); //Add a timer, clock () Every 1 per thousand seconds (1 milliseconds), the value returned by the function is added 1,clocks_per_se in time.h defined as 1000. Two division of values to get the units in secondsprintf"Time used =%.2f\n", (Double) clock ()/clocks_per_sec); return 0;}
Note: The keyboard input time is also counted.
2.3 Chronograph functions