Last active
August 29, 2015 14:01
-
-
Save robertsosinski/6be53360458f92972935 to your computer and use it in GitHub Desktop.
Computing Factorials in Parallel in Go
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
package main | |
import ( | |
"fmt" | |
"math/big" | |
"runtime" | |
) | |
func main() { | |
runtime.GOMAXPROCS(runtime.NumCPU()) | |
list := []int64{20, 18, 20, 22, 20, 19, 20, 21} | |
// Try with these to see your processor cores spike up. | |
// Remember to comment out the `fac` output on line 38! | |
// list := []int64{200000, 180000, 200000, 220000, 200000, 190000, 200000, 210000} | |
factorialCollector(list) | |
} | |
type FactorialResult struct { | |
idx int | |
num int64 | |
fac *big.Int | |
} | |
func factorialCollector(factorials []int64) { | |
rounds := len(factorials) | |
receiver := make(chan FactorialResult, rounds) | |
for idx, num := range factorials { | |
go factorialCalculator(receiver, idx, num) | |
} | |
for i := rounds; i > 0; i-- { | |
result := <- receiver | |
fmt.Println(result.idx, "factorial for", result.num, "is", result.fac) | |
} | |
} | |
func factorialCalculator(receiver chan<- FactorialResult, idx int, num int64) { | |
receiver <- FactorialResult{idx: idx, num: num, fac: factorial(big.NewInt(num))} | |
} | |
func factorial(num *big.Int) *big.Int { | |
return factorialFn(num, big.NewInt(1)) | |
} | |
func factorialFn(num, acc *big.Int) *big.Int { | |
if big.NewInt(0).Cmp(num) == 0 { | |
return acc | |
} else { | |
acc.Mul(acc, num) | |
num.Sub(num, big.NewInt(1)) | |
return factorialFn(num, acc) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment