Fibonacci numbers list

Fibonacci numbers problem

Write a program to compute the Fibonacci sequence number of a given integer. Your algorithm must run in linear time ie O(N).

Fibonacci numbers

What is the fibonacci sequence

Definition: Fibonacci number of (N) is the sum of Fibonacci numbers of (N-1) and (N-2). In other words, the fibonacci numbers list formula:

where

Fibonacci code

The easiest way to solve this problem is by recursion due to the recursive nature of the problem however a recursive solution has an exponential time complexity function of (N). The reason why a recursive solution is very slow is because it recomputes values whenever needed from the scratch and does not utilize the fact that some numbers need not be recomputed every single time as long as we can save and reuse later. Such technique is called memoization which is an optimization technique used to speed up programs by having function calls avoid repeating the calculation of results for previously computed values. For more information you can search for the topic Dynamic Programming. So how can we solve this problem in linear time using memoization. Here is how we will solve this problem: if (N) is zero just return zero otherwise save the first two Fibonacci numbers needed for the calculation of the third Fibonacci number. Keep updating those two numbers as you loop to (N) for example if you need to calculate Fibonacci(5) then Fibonacci(3) and Fibonacci(4) should be calculated along the way while looping to (5)

Fibonacci numbers C++

Here is an example fibonacci number calculator algorithm:

I hope fibonacci numbers got explained in an easy way. Comments ? questions ? pease use the comments section below. Thanks for reading.

Add a Comment

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