Drill

ProblemsTypeScript › warmup

Nth Fibonacci number

easywarmupTypeScript

Return the nth number in the Fibonacci sequence, counting from zero.

fibonacci(n: int) → int

Solve it in the editor →

Where you start

function fibonacci(n: number): number {
  
}

Worked examples

CallResult
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 TypeScript
function fibonacci(n: number): number {
  let a = 0;
  let b = 1;
  for (let i = 0; i < n; i++) [a, b] = [b, a + b];
  return a;
}

The same problem in another language

More warmup problems in TypeScript