Fibonacci in C#

ddanbe

Yes, I know Fibonacci(=sun of a good man) again.
Most famous for his series, but who among you all, know that he was the man who introduced to the Western world, the Arabic numeral system(including zero) in 1202 A.D.? The Italian merchands of those days adored it. It was far more easy to work with than the roman numeral system of course. And it is still in use today.
I did the series a little different with a calculation that gives you any Fibonacci number from zero up to the 93th one. I guess the Convert method does the rounding. Also included here in the code, is a little test loop.
Enjoy!

516 Views
About the Author

Have programmed in Modula-2 on a professional basis in the eighties. Now I am quite fond of C# AND Python!

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            for (Byte n = 0; n < 20; n++)
            {                
                Console.WriteLine("F({0}) = {1}", n, Fib(n));
            }
            Console.ReadKey();
        }


        /// <summary>
        /// Calculates the Nth(starting from zero) Fibonacci number
        /// no overflow error checking
        /// </summary>
        /// <param name="n">n can range from 0 to 93</param>
        /// <returns>F(n)</returns>
        public static UInt64 Fib(Byte n)
        {
            double sqrt5 = Math.Sqrt(5);
            double phi = (sqrt5 + 1) / 2;
            return Convert.ToUInt64((1 / sqrt5) * Math.Pow(phi, n));
        }
    }
}
ddanbe 2,724 Professional Procrastinator Featured Poster

Oops! Fibonacci(=sun of a good man) must be Fibonacci(=son of a good man)

Triryche 0 Newbie Poster

If you get a chance, could you elaborate on the math a bit?

ddanbe 2,724 Professional Procrastinator Featured Poster

I used a variation of Binet's formula.

Triryche 0 Newbie Poster

That explains it. I'm somewhat of a math geek, suprise I never heard of that. I was wondering why you went through all of that instead of simple addition.

Triryche 0 Newbie Poster

I don't understand how Console.WriteLine**("F({0}) = {1}"**, n, Fib(n));
produces F(0),F(1)F(2)...

sepp2k 378 Practically a Master Poster

{0} and {1} are placeholders for the second and third arguments to WriteLine respectively. So {0} is replaced with the value of n (the second argument) and {1} is replaced with the value of Fib(n) (the third argument). So Console.WriteLine("F({0}) = {1}"**, n, Fib(n)) will print F(3) = 6 when n is 3.

For more information see Composite Formatting (MSDN).

PS: If that wasn't your question, please clarify.

Triryche 0 Newbie Poster

Awesome!! That explains it perfectly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.