java - Fibonacci Recursion? -
i have started learn recursion. program i'm asked make should take term input, , output corresponding fibonacci number. have far, it's showing error. what's wrong?
thanks in advance!
private void btnfindnumberactionperformed(java.awt.event.actionevent evt) { int term = integer.parseint(txtinputterm.gettext()); int number = fibonacci(term); txtoutput.settext("fibonacci number " + term + " " + number); } public int fibonacci (int term) { if (term == 1) { return term; } else { int number = fibonacci(term-1) + fibonacci(term-2); return number; } }
imagine fibonacci term being 2. happen?
- term == 1 ? wrong, continue else...
- so try calling
fibonacci(term-1)
( =fibonacci(1)
) +fibonacci(term-2)
( =fibonacci(0)
)
ok, fibonacci(term-1)
( = fibonacci(1)
)...
- term == 1 ? true, returning 1
ok, fibonacci(term-2)
( = fibonacci(0)
)
- term == 1 ? false, because it's zero. , goes downhill there, since numbers negative , never step term == 1.
so, perhaps might wish think again if criteria should equal 1 or perhaps different.
as more technical explanation, since mentioned in comments: when calling method, data stored on called "stack". if call, example, method a, calls b, data (at least) 2 methods stored on stack. if b again calls method, again, again... stack overflow, dreaded stackoverflowexception
. happens when getting return conditions wrong on recursive method.
and last comment: don't recursive methods unless need to. imagine need learn now, in future, don't forget recursion elegant concept - in math, not in coding, tends lead problems (like 1 - , fact calculating fibonacci recursively worst way so).
Comments
Post a Comment