Skip to content

Instantly share code, notes, and snippets.

@parasyte
Created November 15, 2012 09:44
Show Gist options
  • Save parasyte/4077694 to your computer and use it in GitHub Desktop.
Save parasyte/4077694 to your computer and use it in GitHub Desktop.
Fibonacci closure: http://tour.golang.org/#48
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
x, y := 0, 1
return func() int {
x, y = y, x + y
return x
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@shishirmdr
Copy link

Very late but here's my solution. This also makes sure that the pattern starts from 0.

func fibonacci() func() int {
    a, b, c := 0, 1, 0

    return func() int {
        c += a
        a = b
        b = c
  
        return c
    }
}

@vjykrthk
Copy link

vjykrthk commented May 3, 2020

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	result := 0
	initial := 1
	return func() int {
		temp := result
		result += initial
		initial = temp
		return initial
	}
}

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

@AlexandrHeroCoud
Copy link

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	i := 0
	iOne := int(1)
	ret := 0
	return func() int {
		if i == 0{
			i = 1
		}
		iOne = ret
		ret = i + iOne
		i = iOne

		return ret
	}
}

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

@ngocdiep
Copy link

ngocdiep commented Jul 6, 2020

func fibonacci() func() int {
x, y := -1, 0
return func() int {
x, y = y, x + y
return (-1) * x
}
}

@khayru11oh
Copy link

package main
import "fmt"
func main() {
a := 0
for i:=1; i<=1000; {
fmt.Println(i)
a, i = i, i+a
}
}

@raihankhan
Copy link

func fibonacci() func() int {
a := 0
b := 1
return func() int {
defer func() {
fib := a+b
a = b
b = fib
}()
return a
}
}

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

@sina-devel
Copy link

func Fibonacci() func() uint {
	var a, b uint = 1, 0
	return func() uint {
		a, b = b, a+b
		return a
	}
}

@msh2050
Copy link

msh2050 commented Jan 27, 2022

thanks for the gist,it is very much useful
I make Benchmarking for deferent Fibonacci functions and algorithms with running unit test
https://github.com/msh2050/GoFibonacciBench

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment