2

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?

3
  • Did you mean #DEFINE errors ? Commented Jul 2, 2009 at 18:52
  • 2
    Just curious, but why are you returning an int rather than a bool? Commented Jul 2, 2009 at 18:53
  • @Joel I'm guessing he was introduced to C before C#, where bool doesn't exist and integer values 1 and 0 are commonly used for true and false, respectively. Commented Nov 26, 2011 at 19:13

7 Answers 7

18

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.

Sign up to request clarification or add additional context in comments.

Comments

11

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++)

1 Comment

+1 I'm amazed that highest answer and accepted answer don't point out the reason of error. This is the actual problem with his code. He's getting Index out of range exception because of accessing fib[100] while the last item is fib[99].
6

And here is a solution that beats all of yours!

Because, why iteration when you have smart mathematicians doing closed-form solutions for you? :)

static bool IsFibonacci(int number)
{
    //Uses a closed form solution for the fibonacci number calculation.
    //http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

    double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
    int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence

    int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)

    return actualFibonacciNumber == number;
}

Comments

5

Well, for starters your array is only 10 long and you're filling it with ~100 items (out-of-range-exception) - but there are better ways to do this...

for example, using this post:

long val = ...
bool isFib = Fibonacci().TakeWhile(x => x <= val).Last() == val;

Comments

2
int[] fib = new int[10];
for (int i = 2; i <= *100*; i++)

You're going out of the bounds of your array because your loop conditional is too large. A more traditional approach would be to bound the loop by the size of the array:

for (int i = 2; i < fib.Length; i++)

And make your array bigger, but as Marc said, there are better ways to do this, and I would advise you spend some time reading the wikipedia article on Fibonacci numbers.

Comments

2

One thing you can do is check for an early exit. Since you're trying to determine if a given number is in the Fibonacci sequence, you can do bounds checking to exit early.

Example:

static bool isFibonacci(int n)
{
    int[] fib = new int[100];
    fib[0] = 1;
    fib[1] = 1;
    for (int i = 2; i <= fib.Length; i++)
    {
        fib[i] = fib[i - 1] + fib[i - 2];

        if (n == fib[i])
        {
            return true;
        }
        else if (n < fib[i])
        {
            return false;  //your number has been surpassed in the fib seq
        }
    }
    return false;
}

1 Comment

Probably should throw an exception if the end of the array is met: function is not able to give an answer in this case.
1
public static int FibNo(int n) {
    int result = 0; int No = 0; int N1 = 1;

    if (n< 0)
    { throw new ArguementException("number must be a positive value"); }

    if (n <= 1) 
    { result = n; return result; }

    for(int x=1; x < n; x++) 
    { result = No + N1; No = N1; N1=result; }

    return result;

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.