File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 11mod egg_dropping;
2+ mod fibonacci;
23
34pub use self :: egg_dropping:: egg_drop;
5+ pub use self :: fibonacci:: fibonacci;
You can’t perform that action at this time.
0 commit comments