1
+ // src/09-recursion/04-fibonacci.js
2
+
3
+ // iterative approach
4
+ function fibonacciIterative ( n ) {
5
+ if ( n < 0 ) {
6
+ throw new Error ( 'Input must be a non-negative integer' ) ;
7
+ }
8
+ if ( n < 2 ) { return n ; }
9
+
10
+ let prevPrev = 0 ;
11
+ let prev = 1 ;
12
+ let current ;
13
+
14
+ for ( let i = 2 ; i <= n ; i ++ ) { // n >= 2
15
+ current = prev + prevPrev ; // f(n-1) + f(n-2)
16
+ prevPrev = prev ;
17
+ prev = current ;
18
+ }
19
+
20
+ return current ;
21
+ }
22
+
23
+ console . log ( 'fibonacciIterative(2)' , fibonacciIterative ( 2 ) ) ; // 1
24
+ console . log ( 'fibonacciIterative(3)' , fibonacciIterative ( 3 ) ) ; // 2
25
+ console . log ( 'fibonacciIterative(4)' , fibonacciIterative ( 4 ) ) ; // 3
26
+ console . log ( 'fibonacciIterative(5)' , fibonacciIterative ( 5 ) ) ; // 5
27
+
28
+ // recursive approach
29
+ function fibonacci ( n ) {
30
+ if ( n < 0 ) {
31
+ throw new Error ( 'Input must be a non-negative integer' ) ;
32
+ }
33
+ if ( n < 2 ) { return n ; } // base case
34
+ return fibonacci ( n - 1 ) + fibonacci ( n - 2 ) ; // recursive case
35
+ }
36
+
37
+ console . log ( 'fibonacci(5)' , fibonacci ( 5 ) ) ; // 5
38
+
39
+ // memoization approach
40
+ function fibonacciMemoization ( n ) {
41
+ if ( n < 0 ) {
42
+ throw new Error ( 'Input must be a non-negative integer' ) ;
43
+ }
44
+ const memo = [ 0 , 1 ] ;
45
+ const fibonacci = ( n ) => {
46
+ if ( memo [ n ] != null ) return memo [ n ] ;
47
+ return memo [ n ] = fibonacci ( n - 1 ) + fibonacci ( n - 2 ) ;
48
+ } ;
49
+ return fibonacci ( n ) ;
50
+ }
51
+
52
+ console . log ( 'fibonacciMemoization(5)' , fibonacciMemoization ( 5 ) ) ; // 5
53
+
54
+ // to see the output of this file use the command: node src/09-recursion/04-fibonacci.js
0 commit comments