-
Fib numbers recursivly
Anyone suggest a more efficient way to write this recursivly? The common Fibonacci numbers.
class Fibonacci{
long oldNumber = 0;
long lastNumber = 1;
long newNumber;
long Fib(long n){
if ( n == 0 ) return 0;
newNumber = oldNumber + lastNumber;
oldNumber = lastNumber;
lastNumber = newNumber;
System.out.println(newNumber);
return Fib(n-1);
-
gcalvin wrote a great post on how to approach any recursive problem, just yesterday in this forum. I suggest you look in the New To Java forums and search for the word "recursive" and you will find it, it will be very helpful for you for any recursion problem.
For Fibonacci, the base case, will be when n = 0 and when n = 1, where we would simply return 0 and 1.
Next, we try to represent our problem as a smaller instance of itself. Thus, if n does not fall into the cases mentioned above, then the nth Fib number is simply the sum of the previous two numbers. So the last case will be:
Code:
return Fib(n-1) + Fib(n-2);
hope this helps.
Best,
-
Ok
mind showing what code needs to be changed. TYVM
-
what do you mean? You know how to write some basic java correct? The answer I gave you is almost Java code no? Did you at least have a try to change your existing code?
Please post some changes you have done to your code and we can see how to help you. I am relatively new here too, but I know that this forum exists to improve and expand your knowledge of Java, not for people to post code for you.
Posting code is so easy, but then what do you and I gain from it?
Kindly try to have an attempt to change your code, looking at your code, I can say you are very close to achieving what you need.
Post here after that, and I'm sure we can help you proceed.
best,