• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Fibonacci numbers

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic