The largest Fibonacci number that can fit into an int is the 46th one. Now look here:
int largest = fibonacci(46);
That's line 30 in the code I posted earlier. |
I'm not sure that 46 is one of those particularly memorable numbers ... ! (But then I turned to Wikipedia:
https://en.wikipedia.org/wiki/46_(number) )
The Fibonacci sequence starts
a b a+b (b+a+b) ....
and exactly which sequence you get depends on how you set the "seeds" a and b.
Some people (myself included, because then the only repeat is at the start) prefer
1 1 2 3 5 8 ....
and others prefer
0 1 1 2 3 5 ....
In your code
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int fibonacci(int number)
{
int previous = 1;
int current = 1;
int next = 1;
for (int i = 3; i <= number; ++i)
{
next = current + previous;
previous = current;
current = next;
}
return next;
}
|
it is clear that the seeds are 1 and 1, giving the first series (starting 1 1 2 3 ...). Moreover, the
for loop will only run at all if
number is >=3. Hence, if
number = 0, 1, or 2 then this function will just return 1 (the initial value of
next). (From its form, I think this function is really only expecting
number to be 1,2,3 ... etc, not 0).
In your
main() routine:
1 2 3 4
|
for (int i = 0; i < number; ++i)
{
cout << fibonacci(i) << ' ';
}
|
the first three values of i sent to
fibonacci are 0, 1, 2 ... and so your function returns 1, 1, 1 ... as you have coded!