forked from SkienaBooks/Algorithm-Design-Manual-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfib.c
131 lines (100 loc) · 2.37 KB
/
fib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* binomial.c
Compute the binomial coefficients using dynamic programming
begun: February 10, 2002
by: Steven Skiena
*/
#include <stdio.h>
/* [[[ fib_const_cut */
#define MAXN 45 /* largest n or m */
#define UNKNOWN -1 /* contents denote an empty cell */
long f[MAXN+1]; /* array for caching computed fib values */
/* ]]] */
/* computer n choose m */
long binomial_coefficient(int n, int m) {
int i, j; /* counters */
long bc[MAXN][MAXN]; /* table of binomial coefficient values */
for (i = 0; i <= n; i++) {
bc[i][0] = 1;
}
for (j = 0; j <= n; j++) {
bc[j][j] = 1;
}
for (i = 1; i <= n; i++) {
for (j = 1; j < i; j++) {
bc[i][j] = bc[i-1][j-1] + bc[i-1][j];
}
}
return(bc[n][m]);
}
/* [[[ fib_r_cut */
long fib_r(int n) {
if (n == 0) {
return(0);
}
if (n == 1) {
return(1);
}
return(fib_r(n-1) + fib_r(n-2));
}
/* ]]] */
/* [[[ fib_c_cut */
long fib_c(int n) {
if (f[n] == UNKNOWN) {
f[n] = fib_c(n-1) + fib_c(n-2);
}
return(f[n]);
}
/* ]]] */
/* [[[ fib_c_driver_cut */
long fib_c_driver(int n) {
int i; /* counter */
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
f[i] = UNKNOWN;
}
return(fib_c(n));
}
/* ]]] */
/* [[[ fib_dp_cut */
long fib_dp(int n) {
int i; /* counter */
long f[MAXN+1]; /* array for caching computed fib values */
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
f[i] = f[i-1] + f[i-2];
}
return(f[n]);
}
/* ]]] */
long fib_dp2(int n) {
int i; /* counter */
long back1 = 1, back2 = 0; /* last two values of f[n] */
long next; /* placeholder for sum */
if (n == 0) {
return (0);
}
for (i = 2; i < n; i++) {
next = back1 + back2;
back2 = back1;
back1 = next;
}
return(back1 + back2);
}
int main(void) {
int i;
for (i = 0; i < MAXN; i++) {
printf("fib_c(%d) = %ld\n",i, fib_c_driver(i));
}
for (i = 0; i < MAXN; i++) {
printf("fib_dp(%d) = %ld\n",i, fib_dp(i));
}
for (i = 0; i < MAXN; i++) {
printf("fib_dp2(%d) = %ld\n",i, fib_dp2(i));
}
for (i = 0; i < MAXN; i++) {
printf("fib(%d) = %ld\n",i, fib_r(i));
}
return 0;
}