Skip to content

Instantly share code, notes, and snippets.

@braynm
Last active April 6, 2016 05:27
Show Gist options
  • Save braynm/121a289d371049ba8d7abfaebe6c86ff to your computer and use it in GitHub Desktop.
Save braynm/121a289d371049ba8d7abfaebe6c86ff to your computer and use it in GitHub Desktop.
Factorials w/ big numbers in go
package main
import (
"fmt"
"math/big"
"time"
)
func fact(n *big.Int) (result *big.Int) {
b := big.NewInt(0)
c := big.NewInt(1)
if n.Cmp(b) == -1 {
result = big.NewInt(1)
}
if n.Cmp(b) == 0 {
result = big.NewInt(1)
} else {
result = new(big.Int)
result.Set(n)
result.Mul(result, fact(n.Sub(n, c)))
}
return result
}
func main() {
var startTime = time.Now()
ch := make(chan *big.Int)
go func() {
for i := 0; i < 500 ; i++ {
n := big.NewInt(5000)
ch <- fact(n)
} // fmt.Println(fact(n))
}()
var wg sync.WaitGroup
wg.Add(1)
go func(wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 500; i++ {
<-ch
}
}(&wg)
wg.Wait()
fmt.Println("CONSUMED: ", time.Now().Sub(startTime))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment