Created
February 24, 2020 19:20
-
-
Save florianl/1080769dd6dee231cd21ac6a240f45b5 to your computer and use it in GitHub Desktop.
Calculate the fibonacci number in three different ways
This file contains 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 ( | |
"math/rand" | |
"time" | |
) | |
//go:noinline | |
func fibonacciRecursive(n uint32) uint32 { | |
if n < 2 { | |
return n | |
} | |
return fibonacciRecursive(n-1) + fibonacciRecursive(n-2) | |
} | |
//go:noinline | |
func fibonacciCache(n uint32, cache map[uint32]uint32) uint32 { | |
var i uint32 | |
for i = 2; i <= n; i++ { | |
tmp := cache[i-1] + cache[i-2] | |
cache[i] = tmp | |
} | |
return cache[n] | |
} | |
//go:noinline | |
func fibonacciLoop(n uint32) uint32 { | |
var a uint32 = 0 | |
var b uint32 = 1 | |
for i := 0; i < int(n); i++ { | |
a, b = b, a+b | |
} | |
return a | |
} | |
func init() { | |
rand.Seed(time.Now().Unix()) | |
} | |
func main() { | |
for { | |
num := rand.Uint32() % 32 | |
println(fibonacciRecursive(num)) | |
cache := make(map[uint32]uint32) | |
cache[0] = 0 | |
cache[1] = 1 | |
println(fibonacciCache(num, cache)) | |
println(fibonacciLoop(num)) | |
time.Sleep(3 * time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment