Computing a Fibonacci Sequence

date
May 30, 2021
slug
computing a-fibonacci-sequence
status
Published
summary
remember the recursion, how it works and how to spell it.
tags
Coding
type
Post
"Write a function to return an n element in Fibonacci sequence” is one of the most common questions. I'll list two methods below.
Input: A array with first two initials, the total length of the sequence,
Output: The whole sequence
Use while loop:
const fibonacci = (arr, length) => {
  let num1 = arr[0]
  let num2 = arr[1]
  let next = num1 + num2
  let count = 2

  while (count < length) {
    next = num1 + num2
    num1 = num2
    num2 = next
    count++
    arr.push(next)
  }
  return arr
}
Use recursion:
const fibonacci = (arr, length) => {
  if (arr.length >= length) return arr

  const next = arr[arr.length - 2] + arr[arr.length - 1]
  arr.push(next)

  return fibonacci(arr, length) // don't forget to return the function itself
}
 

© Craig Hart 2015 - 2021