Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Fibonacci numbers  RSS feed

 
Stacey Johnson
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
I need help again. Thanks to those who replied on my recursion question. But now I've got bigger fish to fry.
I have to write a nonrecursive method that computes Fibonacci numbers.
The person is suppose to input an index and the application is suppose to compute what Fibonacci number is at that index. The algorithm my text gives me is a follows:
public static long fib(long q) { //I've added this line

f0 = 0;
f1 = 1;

for (int r = 2; r <= q; r++) {
currentFib = f0 + f1;
f0 = f1;
f1 = currentFib;
I've got everything set up accept for the acutal formula to compute. I don't know if I should be using a return statement, if statement or what. I'm still unclear as to exactly how this calculation works. Can somebody please help I'm dying here!
Thanks
Stacey
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stacey, welcome to the ranch.
Your question made me think, i haven't implement the fibonacci alg. since i graduated (2 years ago). it was a good question to get me back in shape.
My advice try to do it yourself, trust me on this. I am not trying to be rude here but it is for your own good. Incase you couldn't do it see this code.
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stacey ...
Your code is almost there; here is the completed method:

The code in bold represents my additions. As you can see, you were almost there: you just needed to declare the variable types and return the result (stored in "f1").
Inside the loop you are taking the sum of the two previous numbers (f0 and f1) and then re-assigning the value of the two previous numbers so you'll be ready for the next loop. The last sum calculated will end up in "f1", so that's what you should return.
There are several ways of composing the loop, but it's always best for you to do your own code so you understand how it works. It's the only way to learn.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!