Hi. Here's two simple
c++ algorithms that calculate the first 100
fibonacci numbers. Sorry they're not more
versatile,
I just started learning to code last week (
Sept 2000). The difference is that one returns two
terms per
cycle, while the other only returns one... I personally prefer the double-return, I think it's
prettier.
One advantage of the
algorithm that returns two is that it can easily be used to
illustrate the
limit of t(n)/t(n-1) as
n approaches
infinity... this expression
converges to a fixed value, sometimes called the
golden ratio.
Update: (November 22nd) I added a new algorithm to generate the sequence recursively. This is less efficient, but it's a nice looking, extremely small solution. (See Bottom.)
Oh yeah, here's the code:
Double Generator Algoritm:
int t1 = 0, t2 = 1;
for (int counter = 0; counter < 50; counter++)
{
cout << t1 << endl << t2 << endl;
t1 += t2; t2 += t1;
}
Single Generator Algoritm:
int t = 0, temp1 = 1, temp2 = 1;
for (int counter = 0; counter < 50; counter++)
{
cout << t << endl;
temp1 = temp2;
temp2 = t;
t = temp1 + temp2;
}
Recursive Algoritm:
This function returns the nth fibonacci number.
int f(int &n)
{
if ((n == 2) || (n == 1))
return(1);
else
return(f(n-1) + f(n-2));
}