Sequence Generation – Iterative

Problem

Given the following sequence of integer numbers:

Write a function that receives the index of a given number in the sequence above and returns the corresponding sequence number for example if index = 2 the function should return 2, if the index = 5 the function should return 8 and so on

Solution

The first two elements in the sequence are the base case in the solution. If index is 0 or 1 we just return 1 otherwise we loop starting from 2 stopping at the given index while adding the previous two elements in the sequence. At the end we return the sum. Please refer to the code below for more details. By the way I did not mention that this is the Fibonacci series on purpose because one might copy and paste the solution from memory.

Code

Here is the code in Perl

Tags:

Add a Comment

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