Factorial in Go
Example for versions
gc-2010-07-14
The example implements both recursive and iterative methods of calculating factorial and a generic function for printing the results of using any of the methods.
package main
import "fmt"
//Recursive Factorial
func factr(n uint64) uint64 {
if (n < 2) { return 1 }
return n * factr(n-1)
}
//Iterative Factorial
func facti(n uint64) uint64 {
var ret uint64 = 1
for ; n > 0; n-- {
ret *= n
}
return ret
}
func printFact(fact func(uint64) uint64) {
for i := 0; i < 17; i++ {
fmt.Printf("%d! = %d\n", i, fact(uint64(i)))
}
}
func main() {
printFact(factr)
fmt.Println("--")
printFact(facti)
}
Comments
]]>blog comments powered by Disqus
]]>