Comp Sci Find the previous Fibonacci number: java

  • Thread starter Thread starter cgrumiea
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The discussion revolves around creating a Java method named prevFib that returns the Fibonacci number preceding a given non-zero Fibonacci number. A user expresses confusion about implementing recursion in Java, especially for the helper method needed to achieve this. Suggestions include starting from scratch to generate Fibonacci numbers until reaching the target number and then looking back one step. This approach is deemed reasonable, and the user is encouraged to code it in Java. The conversation emphasizes the importance of understanding recursion for solving the problem effectively.
cgrumiea
Messages
4
Reaction score
0

Homework Statement


The first several numbers in the "Fibonacci Sequence" are 0, 1, 1, 2, 3, 5, 8, 13, 21, ... Each number is formed by summing the two previous numbers. Define a method named prevFib that takes a non-zero Fibonacci number and returns the Fibonacci number that comes immediately before it in the sequence.

prevFib(21) ==> 13

Hint: use a recursive helper method.

Homework Equations





The Attempt at a Solution


I'm brand new at java and hardly understand the recursion within it. I know scheme, but this is a different ball game. My main question is what I should do for the recursive helper. Or how that will help when finding the previous Fib number. Any help would be appreciated.
 
Physics news on Phys.org
Forget java for a moment! Suppose you were asked to find the Fibonacci number that comes before 1346269, by any means at all. How would you go about doing it?
 
Forgive me if I sound like a total idiot here. I'm just genuinely lost.
I guess one way would be to start from scratch and add everything up until you get there, then look back one. That just seems like the most concrete way to me, since I can't seem to come up with a formula or anything.
 
cgrumiea said:
I guess one way would be to start from scratch and add everything up until you get there, then look back one.
That sounds like a perfectly reasonable algorithm. Now code it up in Java.
 

Similar threads

Replies
4
Views
5K
Replies
11
Views
2K
Replies
3
Views
6K
Replies
5
Views
3K
Replies
12
Views
2K
Replies
1
Views
1K
Replies
6
Views
4K
Back
Top