I was just going through the iterative version of fibonacci series algorithm. I found this following code
int Fibonacci(int n)
{
int f1 = 0;
int f2 = 1;
int fn;
for ( int i = 2; i < n; i++ )
{
fn = f1 + f2;
f1 = f2;
f2 = fn;
}
}
A silly question just raised in my mind. The function above adds two previous numbers and returns the third one and then get variables ready for the next iteration. What if it would be something like this. "Return a number of series which is the sum of previous three numbers" how we can change the above code to find such a number.u
I like recursion. Call me a sadist.
I don't normally answer questions that "smell" like homework, but since someone else already replied this is what I would do:
It can be improved a bit to avoid all the ugly modular arithmetic (which I left in to make the circular nature of the last[] array clear) by changing the loop to this:
It can be optimized a bit more and frankly, there are much better ways to calculate such sequences, as templatetypedef said.
As a hint, notice that the above algorithm works by "cycling" the numbers through some variables. In the above code, at each point you are storing
You then "shift" them over by one step in the loop:
You then "shift" them again in the next loop iteration:
If you want to update the algorithm sum the last three values, think about storing them like this:
Then shift them again:
Then shift them again:
Converting this intuition into code is a good exercise, so I'll leave those details to you.
That said - there is a much, much faster way to compute the nth term of the Fibonacci and "Tribonacci" sequences. This article describes a very clever trick using matrix multiplication to compute terms more quickly than the above loop, and there is code available here that implements this algorithm.
Hope this helps!
If you want to use recursion, you don't need any other parameters: