Ad
Recursion
Mathematics

Problem statement

Write a function fibonacci(n) that takes a positive integer n as input and returns the nth number in the Fibonacci sequence. The Fibonacci sequence is a series of numbers in which each number after the first two is the sum of the two preceding ones. The sequence starts with 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

Constraints

The input integer n will be a positive integer not exceeding 50.

Notes

This problem can be solved using recursion, but using an iterative solution is also a valid approach.

function fibonacci(n) {
  if (n === 0) {
    return 0;
  }
  if (n === 1) {
    return 1;
  }

  return fibonacci(n - 1) + fibonacci(n - 2);
}