Created
February 17, 2018 17:27
-
-
Save laidback/4560bcf75e758b661b5463302692d318 to your computer and use it in GitHub Desktop.
go-factorial created by laidback - https://repl.it/@laidback/go-factorial
This file contains hidden or 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
| // 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