File tree Expand file tree Collapse file tree 1 file changed +12
-1
lines changed
Algorithms/dynamic_programming Expand file tree Collapse file tree 1 file changed +12
-1
lines changed Original file line number Diff line number Diff line change 1+ // Calculates fib(n) such that fib(n) = fib(n - 1) + fib(n - 2)
2+ // fib(0) = fib(1) = 1
3+ // Uses a bottom up dynamic programming approach
4+ // Solve each subproblem once, using results of previous subproblems,
5+ // which are n-1 and n-2 for Fibonacci numbers
6+
7+ // Although this algorithm is linear in space and time as a function
8+ // of the input value n, it is exponential in the size of n as
9+ // a function of the number of input bits
110
211function fib ( n ) {
312 var table = [ ] ;
@@ -6,9 +15,11 @@ function fib(n) {
615 for ( var i = 2 ; i < n ; ++ i ) {
716 table . push ( table [ i - 1 ] + table [ i - 2 ] ) ;
817 }
9- console . log ( "The %dth fibonacci number is %d" , n , table [ n - 1 ] ) ;
18+ console . log ( "Fibonacci #%d = %d" , n , table [ n - 1 ] ) ;
1019}
1120
21+ fib ( 1 ) ;
22+ fib ( 2 ) ;
1223fib ( 200 ) ;
1324fib ( 5 ) ;
1425fib ( 10 ) ;
You can’t perform that action at this time.
0 commit comments