-
Notifications
You must be signed in to change notification settings - Fork 0
/
sieve.go
62 lines (38 loc) · 743 Bytes
/
sieve.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
package main
import "fmt"
func NextPrime() <-chan int {
out := make(chan int, 1)
go func() {
out <- 2
composites := make(map[int][]int)
num := 3
for {
if _, ok := composites[num]; !ok {
out <- num
composites[num * num] = []int{num}
} else {
for _, prime := range composites[num] {
next := num + prime
for next % 2 == 0 {
next += prime
}
if _, ok := composites[next]; ok {
composites[next] = append(composites[next], prime)
} else {
composites[next] = []int{prime}
}
}
delete(composites, num)
}
num += 2
}
}()
return out
}
func main() {
primes := NextPrime()
for i := 0; i < 100; i++ {
<-primes
}
fmt.Println(<-primes)
}