Skip to content

Instantly share code, notes, and snippets.

@esimov
Last active August 7, 2022 00:20
Show Gist options
  • Save esimov/11394032 to your computer and use it in GitHub Desktop.
Save esimov/11394032 to your computer and use it in GitHub Desktop.
Example of parallel factorial computation in Go lang using go routines.
package main
import (
"math/rand"
"fmt"
)
const (
N int = 128
)
func FactorialClosure() func(n uint64)uint64 {
var a, b uint64 = 1, 1
return func(n uint64)uint64 {
if n > 1 {
a, b = uint64(b), uint64(n) * uint64(a)
} else {
return 1
}
return b
}
}
func main() {
arr := make([]int, N)
for i:=0; i < N; i++ {
arr[i] = rand.Intn(100)
}
fact := FactorialClosure()
for i:=uint64(0); i < uint64(N); i++ {
go func(v uint64) {
fmt.Printf("Factorial for %d is : %d \n", uint64(v), fact(uint64(v)))
}(i)
}
}
@ctirouzh
Copy link

ctirouzh commented Aug 7, 2022

Hi, I run this code and get the following result:
Factorial for 5 is : 5
Factorial for 0 is : 1
Factorial for 1 is : 1
Factorial for 2 is : 10
Factorial for 3 is : 24
Factorial for 4 is : 40
Factorial for 21 is : 504
Factorial for 18 is : 720
Factorial for 19 is : 9576
Factorial for 20 is : 14400
Factorial for 23 is : 220248
Factorial for 22 is : 4845456
Factorial for 12 is : 2937600
Factorial for 6 is : 29072736
Factorial for 17 is : 244800
Factorial for 8 is : 8
.
.
.
Factorial for 67 is : 14445548231830011904
Factorial for 72 is : 324846243660431360
Factorial for 109 is : 9223372036854775808
Factorial for 112 is : 18319869227957223424
Factorial for 120 is : 0
Factorial for 73 is : 8892326705834754048
It seems that your solution is not working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment