Created
June 2, 2024 22:17
-
-
Save dorianbayart/ec9df06f60df3b468872bb2f7015e345 to your computer and use it in GitHub Desktop.
Calculate big Fibonacci numbers with BigInt and memoization in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fibonacci = (n) => { | |
// memoization Map: stores all Fibonacci numbers | |
const lookup = new Map() | |
const fib = (n) => { | |
// if the nth number is in the memoization table, return it | |
if (lookup.has(n)) return BigInt(lookup.get(n)) | |
// base case: if n is 0 or 1, return n itself | |
if (n <= 1) return n | |
// recursively calculate the nth Fibonacci number from its 2 previous numbers | |
const res = fib(n - BigInt(1)) + fib(n - BigInt(2)) | |
// store the result in the memoization Map | |
lookup.set(n, res) | |
return res | |
} | |
const result = fib(BigInt(n)) | |
console.log(`The ${ n }th Fibonacci number is ${ result.toString().length } digits long: \n${ result.toString() }`) | |
return result | |
} | |
// example usage: Calculate and print the 7855th Fibonacci number | |
fibonacci(7855) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment