-
Notifications
You must be signed in to change notification settings - Fork 0
/
10.go
executable file
·72 lines (47 loc) · 913 Bytes
/
10.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
package main
// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
//
// Find the sum of all the primes below two million.
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()
sum := 0
for {
prime := <-primes
if prime < 2000000 {
sum += prime
} else {
break
}
}
fmt.Println(sum)
}