C# Fibonaci sequence

Fibonaci Sequence:
 
My co-worker asked me about Fibonaci sequence. And I made the sample code with C#.
Fibonaci sequence is defined that every number is result of addition of two previous numbers in the sequence.
A[n] = A[n – 1] + A[n – 2]
Example: 1, 1, 2, 3, 5…. 


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i< 51; i++)
            {
                Console.Write ("{0} ", fibonachi(i));
            }
            Console.ReadLine();
        }
        static long fibonachi(int n)
        {
            long Previous = 1;
            long prePrevious = 1;
            long result = 1;
            if (n < 1)
            {
                return -1;
            }
            else if (n < 2)
            {
                return result;
            }
            for (int i = 2; i < n; i++)
            {
                result = prePrevious + Previous;
                prePrevious = Previous;
                Previous = result;
            }
            return result;
        }
    }
}
 
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s