Ok so I've never come across recursion before, or if I did it was very briefly and I forgot it. So I've been looking it up to try and understand it and I think I'm starting to get a vague idea of it but it's still hazy in areas. I'm more trying to understand why anyone would need to use it.
As for the Fibonacci sequence I've never heard of it before, I'm not really a maths guy so I'm trying to get this but maybe I'm thinking about it wrong. From what I gather it is a sequence of numbers starting from 0 or 1 as the seed where the next number is always the sum of the previous two numbers.
So that much makes sense to me. But the formula listed for it is confusing me a little, I think I'm missing something...
Seems to be the formula....ok so if I make n in this instance 13 (which is part of the sequence) let's see if this pans out... it should be that 5 + 8 = 13.
13 - 1 = 12
13 - 2 = 11
12 + 11 = 23 ...which is not even in the sequence...where am I going wrong here conceptually?
So maybe it is...
13 - 1 = 12
(n now becomes 12)
12 - 2 = 10
12 + 10 = 22, also not in the sequence...
So to me the only way this makes sense is if Fn refers to a Fibonacci number, in other words
only to numbers in the sequence, and then the sequence is like an array in a way and saying Fn - 1 is the same as saying the previous number in the sequence that is a distance of 1 position away etc...
So 1 postion previous to 13 is 8 and 2 positions previous is 5, add them together and you get 13.
Is this the right way to think about it? It's the only thing that makes sense to me....I'm not really a maths guy...
Ok so I was looking at a tutorial on recursion and this was a solution given to the Fibonacci recurrence in Java
Code:
/**
* Recursively calculate the kth Fibonacci number.
*
* @param k indicates which (positive) Fibonacci number to compute.
* @return the kth Fibonacci number.
*/
private static int fib(int k) {
// Base Cases:
// If k == 0 then fib(k) = 0.
// If k == 1 then fib(k) = 1.
if (k < 2) {
return k;
}
// Recursive Case:
// If k >= 2 then fib(k) = fib(k-1) + fib(k-2).
else {
return fib(k-1) + fib(k-2);
}
}
Ok...so I understand that this method is calling itself inside the body of the method. But what is the purpose of the program? Do you give it a fib number and is it supposed to calculate all of the following fib numbers in the sequence until it becomes too big to store as an integer?? Also if the formula for Fibonacci numbers works the way I think it does in that it is supposed to only count numbers in the sequence then how does this code work if fib(k-1) + fib(k-2) is subtracting 1 or two from the
VALUE of the fib number and not from it's position in the sequence???
Arrgh maybe I'm just thinking about this wrong...anyone clear this up?