|
| 1 | + |
| 2 | +// Path: Fib.ts |
| 3 | +// Fibonacci Series |
| 4 | +// Solution 1 - Slow |
| 5 | +functionfib(n){ |
| 6 | +if(n<=1)return1; |
| 7 | +returnfib(n-1)+fib(n-2); |
| 8 | +} |
| 9 | + |
| 10 | +// Solution 2: fast : Using hash object memoization to store the values of fibonacci series up to n number of times and return the value of nth number in the series if it is already stored in the hash object. |
| 11 | +// If it is not stored in the hash object, |
| 12 | +// then calculate the value of nth number and store it in the hash object. |
| 13 | + |
| 14 | +functionfibhash(num){ |
| 15 | +letnumHash={0:1,1:1}; |
| 16 | +for(leti=2;i<=num;i++){ |
| 17 | +if(numHash[num]){ |
| 18 | +returnnumHash[num]; |
| 19 | +} |
| 20 | +numHash[i]=numHash[i-1]+numHash[i-2]; |
| 21 | +} |
| 22 | +returnnumHash[num]; |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +// Solution 3: fast : Using memoization to store the values of fibonacci series up to n number of times and return the value of nth number in the series if it is already stored in the memoization array. |
| 27 | +// If it is not stored in the memoization array, |
| 28 | +// then calculate the value of nth number and store it in the memoization array. |
| 29 | + |
| 30 | + |
| 31 | +functionfibMemo(num){ |
| 32 | +letmemo=[1,1]; |
| 33 | +for(leti=2;i<=num;i++){ |
| 34 | +if(memo[num]){ |
| 35 | +returnmemo[num]; |
| 36 | +} |
| 37 | +memo[i]=memo[i-1]+memo[i-2]; |
| 38 | +} |
| 39 | +returnmemo[num]; |
| 40 | +} |
| 41 | + |
| 42 | + |