calculating Fibonacci in C#
Asked Answered
I

1

6

I am trying to calculate the Fibonacci sequence in C# in a very simple way, however when it comes to the higher numbers it bugs out and stops working by giving out wrong answers.

ulong num = 1;
ulong lnum = 0;
uint x = 1;

private void Form1_Load(object sender, EventArgs e)
{
    listBox1.Items.Add("(0) " + 1);
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (x <= 1000)
    {
        ulong newnum = lnum + num;
        listBox1.Items.Add("(" + x + ") " + newnum);
        listBox1.SetSelected((int)x, true);
        lnum = num;
        num = newnum;
        x++;
     }
}

I am making it in a way that I can watch it add up the numbers by adding them to a listbox 1 at a time.

Interior answered 16/12, 2012 at 19:38 Comment(0)
K
12

ulong is too small for fibonacchi. You need to use something bigger. .NET 4 added BigInteger, that should allow for arbitrary number size.

For lower .NET versions, you need to find similliar 3rd party implementation

Keegan answered 16/12, 2012 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.