A common whiteboard problem that I have been asked to solve couple times, has been to "write a function to generate the nth Fibonacci number star...
For further actions, you may consider blocking this person and/or reporting abuse
Your iterative solution is wrong, does not work for any number.
onlinegdb.com/HyqiFsZY8
In this case, we manually handle cases for 1 and 2 and start the loop from 2:
Minor error: You are using 0 for the first Fib #, but F(0) = 0 and F(1) = 1
"i" should start with 1, or it should continue till <= n;
The best way to solve this is to point out the relationship between the nth Fibonacci number and the golden ratio. Saves a lot of calculations.
It's also a good opportunity to talk about tail recursion, particularly with regards to Java being a language that doesn't do tail call optimization.
There is a fibonacci algorithm that its O(n) is log(n). Would be good if you cover it?
there is another simple way , just need 2 lines code ,
please reference to here : dev.to/wozaisuzhou/algorithms-chal...