Last active
December 1, 2019 19:15
-
-
Save Azhovan/bbab016c908f371d95872c090fa3fe1b to your computer and use it in GitHub Desktop.
High-performance Fibonacci numbers implementation in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/big" | |
) | |
func main() { | |
fmt.Println(Fib(1000)) | |
} | |
// global to memoize fib | |
var memoize map[int]*big.Int | |
func init() { | |
// initialize the map | |
memoize = make(map[int]*big.Int) | |
} | |
// it will return 1 for anything < 0 as well... | |
// it's calculated recursively and use big.Int since | |
// int64 will quickly overflow | |
func Fib(n int) *big.Int { | |
if n < 0 { | |
return nil | |
} | |
// base case | |
if n < 2 { | |
memoize[n] = big.NewInt(1) | |
} | |
// check if we stored it before | |
// if so return with no calculation | |
if val, ok := memoize[n]; ok { | |
return val | |
} | |
// initialize map then add previous 2 fib values | |
memoize[n] = big.NewInt(0) | |
memoize[n].Add(memoize[n], Fib(n-1)) | |
memoize[n].Add(memoize[n], Fib(n-2)) | |
// return result | |
return memoize[n] | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment