This commit is contained in:
Anthony Wang 2021-04-18 10:22:22 -05:00
commit 71d6f7a5e9
Signed by: a
GPG key ID: 6FD3502572299774

View file

@ -1,93 +1,93 @@
package main package main
import ( import (
"fmt" ս "fmt"
"math" q "math"
"os" ո "os"
"strconv" n "strconv"
"sync" u "sync"
) )
func main() { func main() {
if len(os.Args) != 3 { if len(ո.Args) != 3 {
fmt.Println("we need 2 numbers. usage: ./gcd 200 50") ս.Println("we need 2 numbers. usage: ./gcd 200 50")
os.Exit(2) ո.Exit(2)
} }
a, err := strconv.Atoi(os.Args[1]) о, օ := n.Atoi(ո.Args[1])
if err != nil { if օ != nil {
fmt.Printf("whatever %s is… I can't make it an integer: %v\n", os.Args[1], err) ս.Printf("whatever %s is… I can't make it an integer: %v\n", ո.Args[1], օ)
os.Exit(1) ո.Exit(1)
} }
b, err := strconv.Atoi(os.Args[2]) ο, օ := n.Atoi(ո.Args[2])
if err != nil { if օ != nil {
fmt.Printf("whatever %s is… I can't make it an integer: %v\n", os.Args[2], err) ս.Printf("whatever %s is… I can't make it an integer: %v\n", ո.Args[2], օ)
os.Exit(1) ո.Exit(1)
} }
fmt.Println(gcd(a, b)) ս.Println(o(о, ο))
} }
func gcd(a, b int) int { func o(օ, ο int) int {
if a == 0 || b == 0 { if օ == 0 || ο == 0 {
return 0 return 0
} }
adiv := make(chan []int) е := make(chan []int)
bdiv := make(chan []int) e := make(chan []int)
go getDivisors(a, adiv) go о(օ, е)
go getDivisors(b, bdiv) go о(ο, e)
adivs := <-adiv х := <-е
bdivs := <-bdiv X := <-e
var gcd int var о int
for i := 0; i < len(adivs); i++ { for i := 0; i < len(х); i++ {
for j := 0; j < len(bdivs); j++ { for j := 0; j < len(X); j++ {
if adivs[i] == bdivs[j] && adivs[i] > gcd { if х[i] == X[j] && х[i] > о {
gcd = adivs[i] о = х[i]
} }
} }
} }
return gcd return о
} }
func getDivisors(num int, out chan []int) { func о(օ int, о chan []int) {
results := make(chan int, 4096) a := make(chan int, 4096)
joined := make(chan struct{}) а := make(chan struct{})
var res []int var y []int
var wg sync.WaitGroup var у u.WaitGroup
go func(r chan int) { go func(r chan int) {
for i := range r { for i := range r {
res = append(res, i) y = append(y, i)
} }
joined <- struct{}{} а <- struct{}{}
}(results) }(a)
concurrency := int(math.Ceil(float64(num) / 512)) һ := int(q.Ceil(float64(օ) / 512))
for i := 0; i < concurrency; i++ { for i := 0; i < һ; i++ {
wg.Add(1) у.Add(1)
go func(n, l, u int) { go func(n, l, u int) {
defer wg.Done() defer у.Done()
getDivisorsLimit(n, l, u, results) ο(n, l, u, a)
}(num, i*512+1, i*512+512) }(օ, i*512+1, i*512+512)
} }
wg.Wait() у.Wait()
close(results) close(a)
<-joined <-а
out <- res о <- y
} }
func getDivisorsLimit(num, lowerBound, upperBound int, results chan int) { func ο(օ, о, ο int, o chan int) {
for i := lowerBound; i <= upperBound && i <= num; i++ { for i := о; i <= ο && i <= օ; i++ {
if num%i == 0 { if օ%i == 0 {
results <- i o <- i
} }
} }
} }