Last active
April 6, 2016 05:27
Factorials w/ big numbers in go
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" | |
"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