Problems › JavaScript › warmup
Nth Fibonacci number
Return the nth number in the Fibonacci sequence, counting from zero.
- fib(0) is 0 and fib(1) is 1; every later term is the sum of the two before it.
- n stays within 0..45.
fibonacci(n: int) → int
Where you start
function fibonacci(n) {
}
Worked examples
| Call | Result |
|---|---|
fibonacci(0) | 0 |
fibonacci(1) | 1 |
fibonacci(2) | 1 |
fibonacci(10) | 55 |
Hint
Keep two variables and slide them forward. No recursion needed.
Reference solution in JavaScript
function fibonacci(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}