Skip to content

Instantly share code, notes, and snippets.

@sgade
Created May 23, 2015 20:55
Show Gist options
  • Save sgade/0e9d566304b8906cdede to your computer and use it in GitHub Desktop.
Save sgade/0e9d566304b8906cdede to your computer and use it in GitHub Desktop.
Fibonacci using Goroutines.
package main
import (
"fmt"
)
var cache map[int64]int64 = make(map[int64]int64)
func fib_useCache() bool {
return true
}
func fib_cache(n int64) (r int64, ok bool) {
if fib_useCache() {
r, ok = cache[n]
} else {
r, ok = 0, false
}
return
}
func fibonacci(n int64, c chan int64) {
if n <= 2 {
const result int64 = 1
c <- result
} else {
v, exists := fib_cache(n)
if !exists {
nc := make(chan int64)
var v1, v2 int64
go fibonacci(n - 1, nc)
if ( fib_useCache() ) {
v1 = <- nc
}
go fibonacci(n - 2, nc)
if ( !fib_useCache() ) {
v1 = <- nc
}
v2 = <- nc
v = v1 + v2
cache[n] = v
}
c <- v
}
}
func fib(n int64) (result int64) {
result_c := make(chan int64)
go fibonacci(n, result_c)
result = <- result_c
return
}
func main() {
const n int64 = 20000000
result := fib(n)
output := fmt.Sprintf("Fibonacci(%d): %d", n, result)
fmt.Println(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment