Generate fibonacci series

Lately I have been reading up on interview related questions. One of the other favorite interview questions interviewers have is to “write a program to generate fibonacci set of series for a user defined input number”. In mathematics, the Fibonacci numbers are the numbers in the following integer sequence(Fibonacci sequence)
0,1,1,2,3,5,8,13,21,34,55,89,144………….
So if the user inputs 8 then the output should be
0,1,1,2,3,5,8,13.

Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void GenerateFibonanciSeries()
        {
            var result = new StringHelper().GenerateFibonanciSeries(8);
            Assert.AreEqual(result[0], 0);
            Assert.AreEqual(result[1], 1);
            Assert.AreEqual(result[2], 1);
            Assert.AreEqual(result[3], 2);
            Assert.AreEqual(result[4], 3);
            Assert.AreEqual(result[5], 5);
            Assert.AreEqual(result[6], 8);
            Assert.AreEqual(result[7], 13);
        }
    }

    public class StringHelper
    {
         public List<long> GenerateFibonanciSeries(long numbersToGenerate)
        {
            if (numbersToGenerate <= 0)
            {
                throw new ArgumentException();
            }
            var result = new List<long>();
            long previousNumber = 0;
            long currentNumber = 1;
            result.Add(previousNumber);
            result.Add(currentNumber);
            for (int counter= 2; counter < numbersToGenerate; counter++)
            {
                long tempNumber = currentNumber + previousNumber;
                result.Add(tempNumber);
                previousNumber = currentNumber;
                currentNumber = tempNumber;                
            }
            return result;
        }
    }
}

You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.