Golang. Closures and Fibonacci Numbers


Assignment number 26 in the Go Tour.

Implement a Fibonacci function that returns a function (closure) that returns consecutive Fibonacci numbers (0, 1, 1, 1, 2, 3, 5, …).

Solution:

Fibonacci numbers are when each successive number is the sum of the previous two numbers. At first I made a simple variant in terms of logic, but it does not correlate with the terms of task reference. So I had to redo it.

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {

	n1 := 0
	n2 := 1

	return func() int {

		// return n1 + n2.. save previous values and again

/*
		sum := n1 + n2
		n1 = n2
		n2 = sum
		return sum
		// doesn't start with 0.. our goal is to print _1st_ number, not a summ
		// we must return no the third number, but 1st number! but calculate next ones
*/

		// 1) save n1 as tmp (we are gonna to print-return it!)
		// 2) save n2 as n1
		// 3) complete operation n1 + n2 and save it as n2
		// 4) return tmp

		tmp := n1
		n1 = n2
		n2 = tmp + n2
		return tmp

	}

}

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

And here, by the way, is a program that allows you to find the n-th number of the Fibonacci sequence using recursion:

package main

import "fmt"

func fib(n int) int {

    if n < 2 {
        return n
    }

    return fib(n - 1) + fib (n - 2)
}

func main () {

    var n int

    fmt.Print("Which element of Fibonacci sequence to show? ")

    fmt.Scanf("%d", &n)

    fmt.Println(fib(n))
}

Also common way with for cycle

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {

	r := bufio.NewReader(os.Stdin)

	input, _ := r.ReadString('\n')

	trim := strings.TrimSpace(input)

	n, _ := strconv.Atoi(trim)

	var n1 int = 0
	var n2 int = 1

	for i := 0; i < n; i++ {
		tmp := n1
		n1 = n2
		n2 = tmp + n2
		fmt.Println(tmp)
	}
}

 


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.