Skip to content

Instantly share code, notes, and snippets.

@alexewerlof
Created December 30, 2018 21:04
Show Gist options
  • Save alexewerlof/f6b3fcc67a4a98bf79d80ad29d438179 to your computer and use it in GitHub Desktop.
Save alexewerlof/f6b3fcc67a4a98bf79d80ad29d438179 to your computer and use it in GitHub Desktop.
A fast algorithm for computing the n-th number in the fibonacci series in Node.js
const N = 1000000
function fib(nth) {
if (nth < 3) {
return 1n
}
let a = b = 1n, c
for (let i = 3; i <= nth; i++) {
c = a + b
a = b, b = c
}
return c
}
console.time('computing')
const result = fib(N)
console.timeEnd('computing')
console.log(`Fibonacci #${N} = ${result}\n${result.toString().length} digits`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment