My favorite clean way to implement iteration over Fibonacci numbers is to use first as f i - 1 and second as f i . The Fibonacci equation states that:
f i + 1 = f i + f i - 1
Unless we write this in code, in the next round we increase i . So, we effectively do:
f next i = f current i + f current i - 1
and
f next i - 1 = f current i - 1
How do I implement this in code:
first, second = second, first + second
The first = second corresponds to the update f next i - 1 = f current i - 1 , and the second = first + second corresponds to the update f next i = f current i + f current i - 1 .
Then all that remains for us to do is return the old value to first, so we will save it in the temp variable before doing the update. As a result, we get:
// fibonacci returns a function that returns // successive fibonacci numbers from each // successive call func fibonacci() func() int { first, second := 0, 1 return func() int { ret := first first, second = second, first+second return ret } }
See in action on the go playground .
source share