Victor Avelar
Posted on September 19, 2019
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
💖 💪 🙅 🚩
Victor Avelar
Posted on September 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.