1
+ //The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
1
2
// the algorithm has time complexity of O(n^2), very bad!
2
3
function fibonacci ( position ) {
3
4
// if position is 1 or 2, the number in fibonacci sequence will be 1
4
- if ( position < 3 ) {
5
- return 1 ;
5
+ if ( position <= 1 ) {
6
+ return position ;
6
7
}
8
+
7
9
// else the element in fibonacci sequence will be the sum of
8
10
// element at position(p) (p -1) and (p - 2)
9
11
return fibonacci ( position - 2 ) + fibonacci ( position - 1 ) ;
@@ -24,8 +26,8 @@ function fibonacciMemoized(index, cache) {
24
26
if ( cache [ index ] ) {
25
27
return cache [ index ] ;
26
28
} else {
27
- if ( index < 3 ) {
28
- return 1 ;
29
+ if ( index <= 1 ) {
30
+ return index ;
29
31
} else {
30
32
cache [ index ] =
31
33
fibonacciMemoized ( index - 1 , cache ) +
@@ -41,7 +43,9 @@ function fibonacciMemoized(index, cache) {
41
43
42
44
function fibonacciTabular ( n ) {
43
45
const table = [ 0 , 1 ] ;
44
-
46
+ if ( n <= 1 ) {
47
+ return n ;
48
+ }
45
49
for ( let i = 2 ; i <= n ; i += 1 ) {
46
50
table [ i ] = table [ i - 1 ] + table [ i - 2 ] ;
47
51
}
@@ -54,4 +58,4 @@ function fibonacciTabular(n) {
54
58
// console.log(`Fib normal - ${fibonacci(number)}`);
55
59
// console.log('--');
56
60
// console.log(`Fib memo - ${fibonacciMemoized(number)}`);
57
- // console.log(`Fib table - ${fibonacciTabular(number)}`);
61
+ // console.log(`Fib table - ${fibonacciTabular(number)}`);
0 commit comments