Skip to content

Instantly share code, notes, and snippets.

@yeondudad
Created July 24, 2016 13:45
Show Gist options
  • Save yeondudad/e86c1b2f6eb985e6cb3eea36a7d367f9 to your computer and use it in GitHub Desktop.
Save yeondudad/e86c1b2f6eb985e6cb3eea36a7d367f9 to your computer and use it in GitHub Desktop.
Fibonacci closure with memorization in go
package main
import (
"fmt"
"math/big"
"time"
)
func NewFibonacci() func(x int64) *big.Int {
memo := make(map[int64]*big.Int)
var fib func(x int64) *big.Int
fib = func(x int64) *big.Int {
n, exist := memo[x]
if exist {
return n
} else {
if x < 2 {
memo[x] = big.NewInt(x)
} else {
memo[x] = new(big.Int)
memo[x].Add(fib(x - 1), fib(x - 2))
}
return memo[x]
}
}
return fib
}
func main() {
start := time.Now()
fib := NewFibonacci()
limit := int64(1000)
for i := int64(0); i <= limit; i++ {
fmt.Println(i, ": ", fib(i))
}
elapsed := time.Since(start)
fmt.Println("fibonacci elapsed time: ", elapsed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment