Sunday, 17 January 2016

Kata Day 53: N-th Fibonacci


Problem Description: I love Fibonacci numbers in general, but I must admit I love some more than others.

I would like for you to write me a function that when given a number (n) returns the n-th number in the Fibonacci 
Sequence.

For example:

   nthFibo(4) == 2
Because 2 is the 4th number in the Fibonacci Sequence.

For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

Level:6kyu

Link To Kata: N-th Fibonacci 

Its a pretty easy Kata if you are familiar with Fibonacci numbers. The numbers where the nth term is the sum of previous two terms. We have to find the nth Fibonacci term given n as an input. We start solving this kata by checking if the given n is 1 or 2 in which case we can return 0 or 1 as they are first and second term of the series. If n is greater than 2 then we initialize a count variable equal to 2 and loop until count becomes equal to n. Inside the loop we change the first and second term of the series with second and third term and so on. Each time we increment the count variable by 1.

In the end when we get out of the loop we return the second term of the series as our result to this Kata.

Please go through the code for a better understanding. 

Here is the link to code: Kata Day 53

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment