Skip to content

Instantly share code, notes, and snippets.

@laidback
Created February 17, 2018 17:27
Show Gist options
  • Select an option

  • Save laidback/4560bcf75e758b661b5463302692d318 to your computer and use it in GitHub Desktop.

Select an option

Save laidback/4560bcf75e758b661b5463302692d318 to your computer and use it in GitHub Desktop.
go-factorial created by laidback - https://repl.it/@laidback/go-factorial
// Provide simple time measured factorial function versions
// * iterative
// * recursive
// * tail recursive
package main
import (
"fmt"
"time"
)
func timer(start time.Time, name string) {
elapsed := time.Since(start)
fmt.Printf("%s took: %s\n", name, elapsed)
}
func main() {
fac := fact(10)
fmt.Println(fac)
rec := factrec(10)
fmt.Println(rec)
tail := facttail(10)
fmt.Println(tail)
}
// iterative version
func fact (n uint32) (result uint32) {
defer timer(time.Now(), "fact")
result = 1
for i := n; i > 0; i-- {
result = result * i
}
return result
}
// recursive version
func factrec (n uint32) (result uint32) {
defer timer(time.Now(), "factrec")
return _factrec(n)
}
func _factrec (n uint32) (result uint32) {
if n <= 1 {
return 1
} else {
return n * _factrec(n-1)
}
}
// tail recursive version
func facttail (n uint32) (result uint32) {
defer timer(time.Now(), "facttail")
return _facttail(n, 1)
}
func _facttail(n uint32, acc uint32) (result uint32) {
if n == 0 {
return acc
}
return _facttail(n-1, acc * n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment