Instantly share code, notes, and snippets.

# esimov/factorial.go

Last active June 11, 2023 21:19
Star You must be signed in to star a gist
Factorial calculation in Go lang using three different methods: first traditionally, second with closure and third using memoization. The last method is the fastest between the three.
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 ( "fmt" "time" ) const LIM = 41 var facts [LIM]uint64 func main() { fmt.Println("==================FACTORIAL==================") start := time.Now() for i:=uint64(0); i < LIM; i++ { fmt.Printf("Factorial for %d is : %d \n", i, Factorial(uint64(i))) } end := time.Now() fmt.Printf("Calculation finished in %s \n", end.Sub(start)) //Calculation finished in 2.0002ms fmt.Println("==================FACTORIAL CLOSURE==================") start = time.Now() fact := FactorialClosure() for i:=uint64(0); i < LIM; i++ { fmt.Printf("Factorial closure for %d is : %d \n", uint64(i), fact(uint64(i))) } end = time.Now() fmt.Printf("Calculation finished in %s \n", end.Sub(start)) //Calculation finished in 1ms fmt.Println("==================FACTORIAL MEMOIZATION==================") start = time.Now() var result uint64 = 0 for i:=uint64(0); i < LIM; i++ { result = FactorialMemoization(uint64(i)) fmt.Printf("The factorial value for %d is %d\n", uint64(i), uint64(result)) } end = time.Now() fmt.Printf("Calculation finished in %s\n", end.Sub(start)) // Calculation finished in 0ms } func Factorial(n uint64)(result uint64) { if (n > 0) { result = n * Factorial(n-1) return result } return 1 } func FactorialClosure() func(n uint64)(uint64) { var a,b uint64 = 1, 1 return func(n uint64)(uint64) { if (n > 1) { a, b = b, uint64(n) * uint64(b) } else { return 1 } return b } } func FactorialMemoization(n uint64)(res uint64) { if (facts[n] != 0) { res = facts[n] return res } if (n > 0) { res = n * FactorialMemoization(n-1) return res } return 1 }

### shaleh commented Aug 17, 2017

On go 1.8 there is almost no difference on my Linux box. In the memoization version you do not appear to be saving the output in `facts` and the recursive call is where the time is spent. I came across this gist when searching for 'golang memoization'.

You bigger problem is after 20! you reach the limits of uin64 and the code wraps and gives bogus answers.

### tommyjcarpenter commented Apr 24, 2019

New to go here: how does the first syntax work with (result int)? Does that do some initialization magic?

### elmar-hinz commented Feb 13, 2023

FactorialClosure: a declared but not used

### slava-nikulin commented Jun 11, 2023

FactorialMemoization is not correct. If you want to use DP way, you need to fill facts array. But technically it will not has any differences with regular recursion