Implemented in golang, quite easy to be fair 😄
func GetNthFib(n int) int {
if n == 1 {
return 0
}
if n == 2 {
return 1
}
x, y := 0, 1
for i := 2; i < n; i++ {
x, y = y, x+y
}
return y
}
Explanation
So we check for the first two value as this two are required to be able to build the rest of the sequence.
Once we know it is not 0 (x) or 1 (y), we know that the correct result comes from adding the x+y and moving the values 1 place forward.
The loop starts at 2 because otherwise the results will be offset by 2 iterations (we already check the first two statically).
For example, if the loop starts at 0 and they ask for nth 3, then our result will be 3 which is incorrect as the third position on Fibonacci's sequence is 1.
You can play around with it by using this Golang Playground link
Top comments (1)
Your solution is not correct.
Fibonacci is defined:
Fib(0) = 0
(zero and negative n are more or less optional, depending on your requirements/definition)
Fib(1) = 1
Fib(2) = 1
Fib(n) = (n-1)+(n-2)
Your solution:
Fib(0) = 1
Fib(1) = 0
Fib(2) = 1
Fib(3) = 1
Fib(4) = 2
...
Here is a quick fix: