loading...

Algorithm 101: 3 Ways to Get the Fibonacci Sequence

ebereplenty profile image NJOKU SAMSON EBERE ・2 min read

In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. - Wikipedia

In this article, we don't want to just return the nth term of a sequence, but we want to return the whole sequence as an array depending on the starting points given. Our counting follows the image below:

Alt Text


fibonacci(8); // 21

We are already used to the function call above usually achieved by the code below:


      function fibonacci(n) {
        let firstNum = 0;
        let secondNum = 1;
        let sum = 0;

        for (let i = 0; i <= n - 2; i++) {
          sum = firstNum + secondNum;
          firstNum = secondNum;
          secondNum = sum;
        }

        return sum;
      }

Now, we want to move a little further to returning the whole sequence depending on the starting points (array of 2 numbers) and the limit (nth term) given.


fibonacciSequence([0, 1], 9); //[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

fibonacciSequence([10, 20], 9); //[ 10, 20, 30, 50, 80, 130, 210, 340, 550, 890 ]

Prerequisite

To benefit from this article, you need to possess basic understanding of javascript's arithmetic and array methods.

Let's do this!

  • for...loop
      function fibonacciSequence(array, limit) {
        let finalArray = [...array];

        for (let i = 0; i < limit - 1; i++) {
          let sum = array[0] + array[1];
          finalArray.push(sum);
          array = [array[1], sum];
        }

        return finalArray;
      }
  • while...loop
      function fibonacciSequence(array, limit) {
        let finalArray = [...array];
        let counter = 0;

        while (counter < limit - 1) {
          let sum = array[0] + array[1];
          finalArray.push(sum);
          array = [array[1], sum];
          counter++;
        }

        return finalArray;
      }
  • do...while...loop
      function fibonacciSequence(array, limit) {
        let finalArray = [...array];
        let counter = 0;

        do {
          let sum = array[0] + array[1];
          finalArray.push(sum);
          array = [array[1], sum];
          counter++;
        } while (counter < limit - 1);

        return finalArray;
      }

Conclusion

There are many ways to solve problems programmatically. I will love to know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Discussion

pic
Editor guide