forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.rs
329 lines (300 loc) · 11.2 KB
/
fibonacci.rs
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/// Fibonacci via Dynamic Programming
use std::collections::HashMap;
/// fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn fibonacci(n: u32) -> u128 {
// Use a and b to store the previous two values in the sequence
let mut a = 0;
let mut b = 1;
for _i in 0..n {
// As we iterate through, move b's value into a and the new computed
// value into b.
let c = a + b;
a = b;
b = c;
}
b
}
/// fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn recursive_fibonacci(n: u32) -> u128 {
// Call the actual tail recursive implementation, with the extra
// arguments set up.
_recursive_fibonacci(n, 0, 1)
}
fn _recursive_fibonacci(n: u32, previous: u128, current: u128) -> u128 {
if n == 0 {
current
} else {
_recursive_fibonacci(n - 1, current, current + previous)
}
}
/// classical_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn classical_fibonacci(n: u32) -> u128 {
match n {
0 => 0,
1 => 1,
_ => {
let k = n / 2;
let f1 = classical_fibonacci(k);
let f2 = classical_fibonacci(k - 1);
match n % 4 {
0 | 2 => f1 * (f1 + 2 * f2),
1 => (2 * f1 + f2) * (2 * f1 - f2) + 2,
_ => (2 * f1 + f2) * (2 * f1 - f2) - 2,
}
}
}
}
/// logarithmic_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn logarithmic_fibonacci(n: u32) -> u128 {
// if it is the max value before overflow, use n-1 then get the second
// value in the tuple
if n == 186 {
let (_, second) = _logarithmic_fibonacci(185);
second
} else {
let (first, _) = _logarithmic_fibonacci(n);
first
}
}
fn _logarithmic_fibonacci(n: u32) -> (u128, u128) {
match n {
0 => (0, 1),
_ => {
let (current, next) = _logarithmic_fibonacci(n / 2);
let c = current * (next * 2 - current);
let d = current * current + next * next;
match n % 2 {
0 => (c, d),
_ => (d, c + d),
}
}
}
}
/// Memoized fibonacci.
pub fn memoized_fibonacci(n: u32) -> u128 {
let mut cache: HashMap<u32, u128> = HashMap::new();
_memoized_fibonacci(n, &mut cache)
}
fn _memoized_fibonacci(n: u32, cache: &mut HashMap<u32, u128>) -> u128 {
if n == 0 {
return 0;
}
if n == 1 {
return 1;
}
let f = match cache.get(&n) {
Some(f) => f,
None => {
let f1 = _memoized_fibonacci(n - 1, cache);
let f2 = _memoized_fibonacci(n - 2, cache);
cache.insert(n, f1 + f2);
cache.get(&n).unwrap()
}
};
*f
}
/// matrix_fibonacci(n) returns the nth fibonacci number
/// This function uses the definition of Fibonacci where:
/// F(0) = 0, F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
///
/// Matrix formula:
/// [F(n + 2)] = [1, 1] * [F(n + 1)]
/// [F(n + 1)] [1, 0] [F(n) ]
///
/// Warning: This will overflow the 128-bit unsigned integer at n=186
pub fn matrix_fibonacci(n: u32) -> u128 {
let multiplier: Vec<Vec<u128>> = vec![vec![1, 1], vec![1, 0]];
let multiplier = matrix_power(&multiplier, n);
let initial_fib_matrix: Vec<Vec<u128>> = vec![vec![1], vec![0]];
let res = matrix_multiply(&multiplier, &initial_fib_matrix);
res[1][0]
}
fn matrix_power(base: &Vec<Vec<u128>>, power: u32) -> Vec<Vec<u128>> {
let identity_matrix: Vec<Vec<u128>> = vec![vec![1, 0], vec![0, 1]];
vec![base; power as usize]
.iter()
.fold(identity_matrix, |acc, x| matrix_multiply(&acc, x))
}
// Copied from matrix_ops since u128 is required instead of i32
#[allow(clippy::needless_range_loop)]
fn matrix_multiply(multiplier: &[Vec<u128>], multiplicand: &[Vec<u128>]) -> Vec<Vec<u128>> {
// Multiply two matching matrices. The multiplier needs to have the same amount
// of columns as the multiplicand has rows.
let mut result: Vec<Vec<u128>> = vec![];
let mut temp;
// Using variable to compare lenghts of rows in multiplicand later
let row_right_length = multiplicand[0].len();
for row_left in 0..multiplier.len() {
if multiplier[row_left].len() != multiplicand.len() {
panic!("Matrix dimensions do not match");
}
result.push(vec![]);
for column_right in 0..multiplicand[0].len() {
temp = 0;
for row_right in 0..multiplicand.len() {
if row_right_length != multiplicand[row_right].len() {
// If row is longer than a previous row cancel operation with error
panic!("Matrix dimensions do not match");
}
temp += multiplier[row_left][row_right] * multiplicand[row_right][column_right];
}
result[row_left].push(temp);
}
}
result
}
#[cfg(test)]
mod tests {
use super::classical_fibonacci;
use super::fibonacci;
use super::logarithmic_fibonacci;
use super::matrix_fibonacci;
use super::memoized_fibonacci;
use super::recursive_fibonacci;
#[test]
fn test_fibonacci() {
assert_eq!(fibonacci(0), 1);
assert_eq!(fibonacci(1), 1);
assert_eq!(fibonacci(2), 2);
assert_eq!(fibonacci(3), 3);
assert_eq!(fibonacci(4), 5);
assert_eq!(fibonacci(5), 8);
assert_eq!(fibonacci(10), 89);
assert_eq!(fibonacci(20), 10946);
assert_eq!(fibonacci(100), 573147844013817084101);
assert_eq!(fibonacci(184), 205697230343233228174223751303346572685);
}
#[test]
fn test_recursive_fibonacci() {
assert_eq!(recursive_fibonacci(0), 1);
assert_eq!(recursive_fibonacci(1), 1);
assert_eq!(recursive_fibonacci(2), 2);
assert_eq!(recursive_fibonacci(3), 3);
assert_eq!(recursive_fibonacci(4), 5);
assert_eq!(recursive_fibonacci(5), 8);
assert_eq!(recursive_fibonacci(10), 89);
assert_eq!(recursive_fibonacci(20), 10946);
assert_eq!(recursive_fibonacci(100), 573147844013817084101);
assert_eq!(
recursive_fibonacci(184),
205697230343233228174223751303346572685
);
}
#[test]
fn test_classical_fibonacci() {
assert_eq!(classical_fibonacci(0), 0);
assert_eq!(classical_fibonacci(1), 1);
assert_eq!(classical_fibonacci(2), 1);
assert_eq!(classical_fibonacci(3), 2);
assert_eq!(classical_fibonacci(4), 3);
assert_eq!(classical_fibonacci(5), 5);
assert_eq!(classical_fibonacci(10), 55);
assert_eq!(classical_fibonacci(20), 6765);
assert_eq!(classical_fibonacci(21), 10946);
assert_eq!(classical_fibonacci(100), 354224848179261915075);
assert_eq!(
classical_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_logarithmic_fibonacci() {
assert_eq!(logarithmic_fibonacci(0), 0);
assert_eq!(logarithmic_fibonacci(1), 1);
assert_eq!(logarithmic_fibonacci(2), 1);
assert_eq!(logarithmic_fibonacci(3), 2);
assert_eq!(logarithmic_fibonacci(4), 3);
assert_eq!(logarithmic_fibonacci(5), 5);
assert_eq!(logarithmic_fibonacci(10), 55);
assert_eq!(logarithmic_fibonacci(20), 6765);
assert_eq!(logarithmic_fibonacci(21), 10946);
assert_eq!(logarithmic_fibonacci(100), 354224848179261915075);
assert_eq!(
logarithmic_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
/// Check that the itterative and recursive fibonacci
/// produce the same value. Both are combinatorial ( F(0) = F(1) = 1 )
fn test_iterative_and_recursive_equivalence() {
assert_eq!(fibonacci(0), recursive_fibonacci(0));
assert_eq!(fibonacci(1), recursive_fibonacci(1));
assert_eq!(fibonacci(2), recursive_fibonacci(2));
assert_eq!(fibonacci(3), recursive_fibonacci(3));
assert_eq!(fibonacci(4), recursive_fibonacci(4));
assert_eq!(fibonacci(5), recursive_fibonacci(5));
assert_eq!(fibonacci(10), recursive_fibonacci(10));
assert_eq!(fibonacci(20), recursive_fibonacci(20));
assert_eq!(fibonacci(100), recursive_fibonacci(100));
assert_eq!(fibonacci(184), recursive_fibonacci(184));
}
#[test]
/// Check that classical and combinatorial fibonacci produce the
/// same value when 'n' differs by 1.
/// classical fibonacci: ( F(0) = 0, F(1) = 1 )
/// combinatorial fibonacci: ( F(0) = F(1) = 1 )
fn test_classical_and_combinatorial_are_off_by_one() {
assert_eq!(classical_fibonacci(1), fibonacci(0));
assert_eq!(classical_fibonacci(2), fibonacci(1));
assert_eq!(classical_fibonacci(3), fibonacci(2));
assert_eq!(classical_fibonacci(4), fibonacci(3));
assert_eq!(classical_fibonacci(5), fibonacci(4));
assert_eq!(classical_fibonacci(6), fibonacci(5));
assert_eq!(classical_fibonacci(11), fibonacci(10));
assert_eq!(classical_fibonacci(20), fibonacci(19));
assert_eq!(classical_fibonacci(21), fibonacci(20));
assert_eq!(classical_fibonacci(101), fibonacci(100));
assert_eq!(classical_fibonacci(185), fibonacci(184));
}
#[test]
fn test_memoized_fibonacci() {
assert_eq!(memoized_fibonacci(0), 0);
assert_eq!(memoized_fibonacci(1), 1);
assert_eq!(memoized_fibonacci(2), 1);
assert_eq!(memoized_fibonacci(3), 2);
assert_eq!(memoized_fibonacci(4), 3);
assert_eq!(memoized_fibonacci(5), 5);
assert_eq!(memoized_fibonacci(10), 55);
assert_eq!(memoized_fibonacci(20), 6765);
assert_eq!(memoized_fibonacci(21), 10946);
assert_eq!(memoized_fibonacci(100), 354224848179261915075);
assert_eq!(
memoized_fibonacci(184),
127127879743834334146972278486287885163
);
}
#[test]
fn test_matrix_fibonacci() {
assert_eq!(matrix_fibonacci(0), 0);
assert_eq!(matrix_fibonacci(1), 1);
assert_eq!(matrix_fibonacci(2), 1);
assert_eq!(matrix_fibonacci(3), 2);
assert_eq!(matrix_fibonacci(4), 3);
assert_eq!(matrix_fibonacci(5), 5);
assert_eq!(matrix_fibonacci(10), 55);
assert_eq!(matrix_fibonacci(20), 6765);
assert_eq!(matrix_fibonacci(21), 10946);
assert_eq!(matrix_fibonacci(100), 354224848179261915075);
assert_eq!(
matrix_fibonacci(184),
127127879743834334146972278486287885163
);
}
}