JS Algorithm – Fibonacci series

Print out the n-th entry in the fibonacci series. The fibonacci series is an ordering of numbers where each number is the sum of the preceeding two.

For example, the sequence [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] forms the first ten entries of the fibonacci series.

Example:

First solution:

fib(4) === 3

function fib(n) {
  // Initializing result array
  let result = [0, 1];

  // Go from first position of the array until i < n
  for (let i = 0; i < n; i++) {
    // Each cycle
    // Sum save the sum of current item and last item of the array
    let sum = result[i] + result[result.length - 1];

    // Adding sum to the array (this will be last position now)
    result.push(sum);
  }

  // Printing fibonacci serie
  console.log('fibonacci serie -->', result)

  // Returning the result
  return result[result.length - 2];
}

fib(4);

Result:

Second solution:

function fib(n) {
   // Initializing result array
  let result = [0, 1];

  for (let i = 2; i <= n; i++) {
    // For each cycle

    // Getting the last element of the array
    const a = result[i - 1];

    // getting the penultimate element of the array
    const b = result[i - 2];

    // Saving the sum of a and b into the array
    result.push(a + b);
  }

  // Returning the result
  return result[result.length - 1];
}

fib(4);

Result:

Third solution:

function fib(n) {
  // Only when n is 0, 1
  if (n < 2) {
    return n;
  }
  // Call the function again with less number
  return fib(n - 1) + fib(n - 2);
}

fib(4);

Result:

By Cristina Rojas.