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:
int getNthFib(int n) { if (n == 1) return 0; if (n == 2) return 1; int prevPrev = 0; int prev = 1; int currentNumber; for (int i = 2; i < n; i++) { currentNumber = prevPrev + prev; prevPrev = prev; prev = currentNumber; } return currentNumber; }
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;
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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;