-
Notifications
You must be signed in to change notification settings - Fork 0
/
perfect.go
74 lines (62 loc) · 1.07 KB
/
perfect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"log"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
//max, err := strconv.ParseInt(os.Args[1], 10, 32)
//if err != nil {
// log.Fatal(err)
//}
max := 200000
maker(int(max))
}
func maker(max int) {
numWorkers := runtime.NumCPU()
perfect := make(chan int, numWorkers)
numbers := make(chan int, max)
done := make(chan struct{}, numWorkers)
for i := 1; i <= max; i++ {
numbers <- i
}
close(numbers)
for i := 0; i < numWorkers; i++ {
log.Println("Worker ", i)
go worker(numbers, perfect, done)
}
numDone := 0
for {
select {
case number := <-perfect:
{
fmt.Println(number)
}
case <-done:
{
log.Println("Worker ", numDone, " done")
numDone += 1
if numDone == numWorkers {
return
}
}
}
}
}
func worker(numbers, perfect chan int, done chan struct{}) {
for num := range numbers {
sum := 0
for i := 1; i < num; i++ {
if (num % i) == 0 {
sum = sum + i
}
}
//fmt.Println(num)
//fmt.Println(sum)
if sum == num {
perfect <- num
}
}
done <- struct{}{}
}