Skip to content

Instantly share code, notes, and snippets.

@benkoshy
Created December 31, 2024 00:05
Show Gist options
  • Save benkoshy/ab0471e1c73152a1dc7f3e9b0430a8df to your computer and use it in GitHub Desktop.
Save benkoshy/ab0471e1c73152a1dc7f3e9b0430a8df to your computer and use it in GitHub Desktop.
Go - Tour exercise - Fibonacci

References:

package main

import "fmt"

func fibonacci() func() int {
	n_minus_2, n_minus_1 := 0, 1

	current := 0

    return func() int {
        current = n_minus_2 + n_minus_1 // calculate current "fibonacci" number

        // update previous numbers
        // do this after calculating the current number
        n_minus_2, n_minus_1 = n_minus_1, current        

        return current       
    }

}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}

// This implementation starts at 1
// Returns:
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// 89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment