|
|
Definition 3.3 (n!)
If n > 1: n! := (n-1)! * n If n = 1: n! := 1
If we want to calculate n!, we can use the following recursive algorithm:
Function n_factorial(n)
What is the result of:
n_factorial(3): 6 n_factorial(10): 3628800 n_factorial(0): not defined n_factorial(-1): not defined
In C:
1
2 int n_factorial(int n)
3 {
4 if ( n == 1 )
5 return (1);
6 else
7 return ( n * n_factorial(n -- 1 ) );
8 }
9
10 int main(void)
11 {
12 int input; /* n */
13 int result; /* n! */
14
15 printf("n: ");
16 scanf("%d", &input);
17 result = n_factorial(input);
18
19 printf("n_factorial(%d) = %d\n", input, result );
20 }
Let the program run:
% factorial n: 6 n_factorial(6) = 720 % factorial n: 10 n_factorial(10) = 3628800 % factorial n: 22 n_factorial(22) = -522715136 % factorial n: 0 Segmentation Fault (core dumped) % ls -l core -rw-r--r-- 1 bischof cs 8443456 Oct 15 11:02 core
|
|
Last modified 22/May/97