File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
Algorithms/dynamic_programming Expand file tree Collapse file tree 1 file changed +25
-0
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
10+
11+ function fib ( n ) {
12+ var table = [ ] ;
13+ table . push ( 1 ) ;
14+ table . push ( 1 ) ;
15+ for ( var i = 2 ; i < n ; ++ i ) {
16+ table . push ( table [ i - 1 ] + table [ i - 2 ] ) ;
17+ }
18+ console . log ( "Fibonacci #%d = %d" , n , table [ n - 1 ] ) ;
19+ }
20+
21+ fib ( 1 ) ;
22+ fib ( 2 ) ;
23+ fib ( 200 ) ;
24+ fib ( 5 ) ;
25+ fib ( 10 ) ;
You can’t perform that action at this time.
0 commit comments