6.3 Calculate Fibonacci sequence

The problem

The Fibonacci Sequence is the series of numbers:

1, 1, 2, 3, 5, 8, 13, 21, 34, …

The next number is found by adding up the two numbers before it.

  • The 2 is found by adding the two numbers before it (1+1)
  • The 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!

Our problem is to calculate the 100th number in the fibonacci sequence.

The code


List<Decimal> fibo = new List<Decimal>{1, 1}; //initialize first two numbers
for(Integer i = 2; i < 100; i++)
{
    Decimal nextFiboNum = fibo[i-1] + fibo[i-2]; //sum of previous two numbers
    fibo.add(nextFiboNum); //Add the new number into sequence
}    

System.debug('The 100th number is: ' + fibo[99]); //100th number's index is 99

Your result should be 354224848179261915075. Make sure you use Decimal here. Because the number is too large to be held in an Integer.

A bit explanation

The grammar is actually all introduced in our previous posts. We just calculate the new Fibonacci number based on previous two numbers. Then add it into the list. We can fetch the number later by using the index.

Exercise

Think about today’s solution. Is there a way to get the 100th Fibonacci number without using a list? Try writing the code.

Next Post

6.4 Merge two sorted list

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Comments

  1. livingathisfeet.org - June 15, 2017 @ 7:33 am

    This definition explains the Fibonacci sequence and discusses the significance of its patterns throughout the natural world and in human endeavors such as design.

Leave a Reply

Your email address will not be published / Required fields are marked *