Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# fibonacci function returning errors

I am practising a C# console application, and I am trying to get the function to verify if the number appears in a fibonacci series or not but I'm getting errors.

What I did was:

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine(isFibonacci(20));
    }
    static int isFibonacci(int n)
    {
        int[] fib = new int[100];
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i <= 100; i++)
        {
            fib[i] = fib[i - 1] + fib[i - 2];

            if (n == fib[i])
            {
                return 1;
            }



        }
        return 0;
    }
}

Can anybody tell me what am I doing wrong here?

like image 532
jarus Avatar asked Aug 14 '26 08:08

jarus


2 Answers

Here's a fun solution using an infinite iterator block:

IEnumerable<int> Fibonacci()
{
   int n1 = 0;
   int n2 = 1;

   yield return 1;
   while (true)
   {
      int n = n1 + n2;
      n1 = n2;
      n2 = n;
      yield return n;
   }
}

bool isFibonacci(int n)
{
    foreach (int f in Fibonacci())
    {
       if (f > n) return false;
       if (f == n) return true;
    }
}

I actually really like this kind of Fibonacci implementation vs the tradition recursive solution, because it keeps the work used to complete a term available to complete the next. The traditional recursive solution duplicates some work, because it needs two recursive calls each term.

like image 182
Joel Coehoorn Avatar answered Aug 16 '26 21:08

Joel Coehoorn


The problem lies in <= the following statement:

for (int i = 2; i <= 100; i++)

more to the point the =. There is no fib[100] (C# zero counts) so when you check on i=100 you get an exception.

the proper statement should be

for (int i = 2; i < 100; i++)

or even better

for (int i = 2; i < fib.Length; i++)
like image 23
Justin Avatar answered Aug 16 '26 20:08

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!