Skip to content

Commit e2b545f

Browse files
JarredAllenAnshulMalik
authored andcommitted
Fibonacci number (TheAlgorithms#77)
Nth Fibonacci number
1 parent 37614da commit e2b545f

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/// Fibonacci via Dynamic Programming
2+
3+
/// fibonacci(n) returns the nth fibonacci number
4+
/// This function uses the definition of Fibonacci where:
5+
/// F(0) = F(1) = 1 and F(n+1) = F(n) + F(n-1) for n>0
6+
///
7+
/// Warning: This will overflow the 128-bit unsigned integer at n=186
8+
pub fn fibonacci(n: u32) -> u128 {
9+
// Use a and b to store the previous two values in the sequence
10+
let mut a = 0;
11+
let mut b = 1;
12+
for i in 0..n {
13+
// As we iterate through, move b's value into a and the new computed
14+
// value into b.
15+
let c = a + b;
16+
a = b;
17+
b = c;
18+
}
19+
b
20+
}
21+
22+
#[cfg(test)]
23+
mod tests {
24+
use super::fibonacci;
25+
26+
#[test]
27+
fn test_fibonacci() {
28+
assert_eq!(fibonacci(0), 1);
29+
assert_eq!(fibonacci(1), 1);
30+
assert_eq!(fibonacci(2), 2);
31+
assert_eq!(fibonacci(3), 3);
32+
assert_eq!(fibonacci(4), 5);
33+
assert_eq!(fibonacci(5), 8);
34+
assert_eq!(fibonacci(10), 89);
35+
assert_eq!(fibonacci(20), 10946);
36+
assert_eq!(fibonacci(100), 573147844013817084101);
37+
assert_eq!(fibonacci(184), 205697230343233228174223751303346572685);
38+
}
39+
}

src/dynamic_programming/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
mod egg_dropping;
2+
mod fibonacci;
23

34
pub use self::egg_dropping::egg_drop;
5+
pub use self::fibonacci::fibonacci;

0 commit comments

Comments
 (0)