PDA

View Full Version : Need a little help with this C++


TheReaper
03-03-2005, 02:50 AM
Hey guys, I was wondering if any of you could help me figure out the most efficient way of doing the following with an Array in C++

Fibonacci Sequence (Array application)
A Fibonacci sequence is a numerical sequence such that after the second element all numbers are equal to the sum of the previous two elements.



1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...



Write a program to calculate and print the first 20 elements of this sequence.

I'm starting on it after I post this message. Just thought some of you could help me out

Thanks in advance...

_Aerospace_Eng_
03-03-2005, 02:53 AM
don't expect us to give u the code, we may be able to help u with any code that you have provided that is causing u a problem, but i advise that u read this post http://www.codingforums.com/showthread.php?t=53446 as to what you are asking help with seems like a homework assignment

cfc
03-03-2005, 04:43 AM
I just wrote one as a test to see if I was still capable of basic C++, and I only found myself questioning why I bothered when I've been doing some PHP and Java coding for a while now :p . It's not like C++ is ridiculously harder on such a basic level or anything, but enough of that;

As a hint, think of every term in the sequence as an array element, keeping in mind that tn = tn-1 + tn-2 for n > 1, where t0=0 and t1=1

Spookster
03-03-2005, 06:15 AM
For homework assignments like these half of the goal of it is to teach problem solving. I can't even remember which language I had to write this one in when I did it in college. I think I had to do it in either Java or assembly or maybe both.

jkd
03-03-2005, 07:21 AM
There are 3 ways of doing efficient Fibonacci essentially.

Recursive-based calculations with either dynamic programming or a fibonacci pair generator (otherwise calculation branches are repeated):
f(n) = f(n-2) + f(n-1)
with some base cases.

Forward-based calculations:
f(n) = f(n-2) + f(n-1) => f(n+2) = f(n) + f(n+1)
Then you just explicitly set f(0) and f(1), then iterate upwards.

Explicitly. You can simply see that [T_n T_(n+1)] = [1 1; 0 1]^n * [1 1]
It is then pretty simple if you've taken linear algebra to diagnolize the matrix by finding the eigenvalues to get a closed form for T_n, which happens to be:
1/sqrt(5) * ( ((1+sqrt(5))/2)^n - ((1-sqrt(5))/2)^n )

But that isn't really computer programming, that's just plugging in a math formula. Without a doubt you are asked to either do the iterative method or the recursive method.