|
| 1 | +# 0001 MemoizedNthNumberFibonacci ( L-A ) |
| 2 | + |
| 3 | +## Problem |
| 4 | + |
| 5 | +Create a function that return the nth fibonacci number with [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type. |
| 6 | + |
| 7 | +Since the 100th fibonacci number larger than maximum integer you need to use [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
| 8 | + |
| 9 | +This must be fast when running `MemoizedNthNumberFibonacci(100)` |
| 10 | + |
| 11 | +This must be faster than `NthNumberFibonacci` |
| 12 | + |
| 13 | +Fibonacci starts with `0` and `1` |
| 14 | + |
| 15 | +Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2) |
| 16 | + |
| 17 | +## Test Cases |
| 18 | + |
| 19 | +- MemoizedNthNumberFibonacci(10) // 55n |
| 20 | +- MemoizedNthNumberFibonacci(6) // 8n |
| 21 | +- MemoizedNthNumberFibonacci(0) // 0n |
| 22 | +- MemoizedNthNumberFibonacci(1) // 1n |
| 23 | +- MemoizedNthNumberFibonacci(2) // 1n |
| 24 | +- MemoizedNthNumberFibonacci(3) // 2n |
| 25 | +- MemoizedNthNumberFibonacci(63) // 6557470319842n |
| 26 | +- MemoizedNthNumberFibonacci(71) // 308061521170129n |
| 27 | +- MemoizedNthNumberFibonacci(78) // 8944394323791464n |
| 28 | +- MemoizedNthNumberFibonacci(100) // 354224848179261915075n |
| 29 | +- MemoizedNthNumberFibonacci(137) // 19134702400093278081449423917n |
| 30 | +- MemoizedNthNumberFibonacci(200) // 280571172992510140037611932413038677189525n |
| 31 | + |
| 32 | +## Solution |
| 33 | + |
| 34 | +```javascript |
| 35 | +const MemoizedNthNumberFibonacci = (n, memo = {}) => { |
| 36 | + if (n <= 0) return BigInt(0) |
| 37 | + if (n <= 1) return BigInt(1) |
| 38 | + |
| 39 | + if (memo[n]) { |
| 40 | + return memo[n] |
| 41 | + } |
| 42 | + |
| 43 | + const result = |
| 44 | + MemoizedNthNumberFibonacci(n - 2, memo) + |
| 45 | + MemoizedNthNumberFibonacci(n - 1, memo) |
| 46 | + |
| 47 | + memo[n] = result |
| 48 | + |
| 49 | + return result |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +## References |
| 54 | + |
| 55 | +- [Fibonacci Wikipedia](https://en.wikipedia.org/wiki/Fibonacci_number) |
| 56 | +- [Memoization Wikipedia](https://en.wikipedia.org/wiki/Memoization) |
| 57 | +- [Recursive MDN](https://developer.mozilla.org/en-US/docs/Glossary/Recursion) |
| 58 | +- [BigInt MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
| 59 | +- [Memoization FreeCodeCamp](https://www.freecodecamp.org/news/understanding-memoize-in-javascript-51d07d19430e/) |
| 60 | + |
| 61 | +## Problem Added By |
| 62 | + |
| 63 | +- [GitHub](https://www.github.com/kennarddh) |
| 64 | + |
| 65 | +## Contributing |
| 66 | + |
| 67 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 68 | + |
| 69 | +Please make sure to update tests as appropriate. |
0 commit comments