Tuesday, November 28, 2017


Generate fibonacci Series (c# / .NET)


This function is for the beginners as a sample function to generate the Fibonacci series in c#. It takes a number 'n' as an argument ( i.e count of series ) and returns a dictionary with index and values. The basic algorithm is used to calculate the series. Also, the limitations and comments are written within the code.

// returns a dictionary with index and value of Fibonacci series for 'n' counts.
// Currently, the value should not be greater than 9223372036854775807, as we are using Int64 a value type. 
        public Dictionary<int,Int64> GetFibonacciSeries(int n)
        {
            // declaration of variables
            Int64 a = 0, b = 1, temp = 0;

            // declare returnlist as dictionary. It returns a dictionary with index and value of Fibonacci series.
            Dictionary<int, Int64> returnList = new Dictionary<int, Int64>();

            // by default add 0 and 1 to the dictionary.
            returnList.Add(1, a);
            returnList.Add(2, b);

            // perform calculations for remaining counts.
            for (int i = 3; i <= n; i++)
            {
                temp = a + b;
                returnList.Add(i, temp);
                a = b; b = temp;
            }

            // returns the populated dictionary.
            return returnList;
        }

No comments:

Post a Comment