Skip to content

Instantly share code, notes, and snippets.

@dorianbayart
Created June 2, 2024 22:17
Show Gist options
  • Save dorianbayart/ec9df06f60df3b468872bb2f7015e345 to your computer and use it in GitHub Desktop.
Save dorianbayart/ec9df06f60df3b468872bb2f7015e345 to your computer and use it in GitHub Desktop.
Calculate big Fibonacci numbers with BigInt and memoization in JavaScript
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