Fibonacci numbers in Go
Example for versions
gc-2010-07-14
This example implements all three methods of calculating Fibonacci numbers — recursive, iterative and Binet’s formula. Besides, a generic function for printing results of using any of the functions is defined.
package main
import ("fmt"
"math")
//Fibonacci Recursive
func fibr(n int) int {
if n < 2 { return 1 }
return fibr(n-2) + fibr(n-1)
}
//Fibonacci Iterative
func fibi(n int) int {
var a, b int = 1, 1
for i := 0; i < n; i++ {
a, b = b, a+b
}
return a
}
//Fibonacci Binet
func fibb(n int) int {
g := (1 + math.Sqrt(5)) / 2
ret := (math.Pow(g, float64(n)) - math.Pow(1-g, float64(n))) / math.Sqrt(5)
return int(ret)
}
type fibfunc func(int) int
//Implements a general printing method for fibonacci functions
func printFib(fib fibfunc, a, b int) {
for i := a; i < b; i++ {
fmt.Printf("%d, ", fib(i))
}
fmt.Println("...")
}
func main() {
printFib(fibr, 0, 16)
printFib(fibi, 0, 16)
printFib(fibb, 1, 17)
}
Comments
]]>blog comments powered by Disqus
]]>