Calculate Fibonacci numbers
Return the nth Fibonacci number with memoized recursion.
function fibonacci(n, memo = {}) { return memo[n] || (n <= 2 ? 1 : (memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo))); }
Input & expected output
Input
10Expected output
55The edge case
Input
78Expected output
8944394323791464Know the limits
- The lab stops at n = 78, the largest Fibonacci number below Number.MAX_SAFE_INTEGER; use BigInt beyond it.
- fibonacci(1) and fibonacci(2) are 1; n = 0 also returns 1 here.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Calculate Fibonacci numbers from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Caps n at 78 to stay below Number.MAX_SAFE_INTEGER. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clamp a number to a range — Keep a number inside an inclusive minimum and maximum.
- Round to a number of digits — Apply decimal scaling and JavaScript rounding for display-oriented values.
- Add an ordinal suffix to a number — Append st, nd, rd or th to a positive integer.