1

Quick Question, the code included is returning a Fibonacci value but it's the wrong value, it's off by 2, e.g. the user enters ten and 89 is returned, instead of 34. Basically I just want to return the Fibonacci value of the value entered by the user ?

Can anyone spot the problem ? Thanks

var Newmodel = new FibonacciModel();

int a = 0;
int b = 1;
for (int i = 0; i < model.InputFromUser; i++)
{
    model.FibonacciValue = a + b;
    a = b;
    b = model.FibonacciValue;
}

Newmodel.InputFromUser = model.InputFromUser;
Newmodel.FibonacciValue = model.FibonacciValue;

return View(Newmodel);
Alberto
  • 15,626
  • 9
  • 43
  • 56
mkell
  • 711
  • 2
  • 13
  • 31

1 Answers1

6

First and second Fibonacci values should not be calculated:

int a = 0;
int b = 1;

switch(model.InputFromUser)
{
   case 0: model.FibonacciValue = a; break;
   case 1: model.FibonacciValue = b; break;
   default:
       for (int i = 2; i < model.InputFromUser; i++)
       {
           model.FibonacciValue = a + b;
           a = b;
           b = model.FibonacciValue;
       }
       break;

}

Also I suggest you to move Fibonacci value calculation to separate method:

private int CalculateFibonacciValue(int index)
{
    if (index < 0)
        throw new ArgumentException();

    int a = 0;
    int b = 1;
    int value = 0; 

    if (index == 0)
        return a;

    if (index == 1)
        return b;

    for(int i = 2; i <= index; i++)
    {
        value = a + b;
        a = b;
        b = value;        
    }

    return value;
}

That will make code more clean:

model.FibonacciValue = CalculateFibonacciValue(model.InputFromUser);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459