Skip to content

Instantly share code, notes, and snippets.

@ujjwalt
Last active October 13, 2015 03:57
Show Gist options
  • Save ujjwalt/4135197 to your computer and use it in GitHub Desktop.
Save ujjwalt/4135197 to your computer and use it in GitHub Desktop.
A concurrent implementation of Sieve of Eratosthenes
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s max_num", os.Args[0])
return
}
maxNum, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Print(err)
return
} else {
fmt.Printf("Primes below %d\n", maxNum)
}
// for every n < maxnum create a sieve for it and pass to a closure which pushes back multiples of n.
// These values are deleted from a prepared m
m := make(map[int]bool, maxNum)
// ch := make(chan int, maxNum)
for i := 2; i < maxNum; i++ {
m[i] = true
}
ch := make(chan int, maxNum-2)
for i := 2; i < maxNum; i++ {
go func(n int, ch chan int) {
for i := 2; i*n < maxNum; i++ {
delete(m, i*n)
}
ch <- 0
}(i, ch)
}
for i := 2; i < maxNum; i++ {
<-ch // safer since the map is only traversed after all go routines have exited
}
for k := range m {
fmt.Println(k)
}
}
@ujjwalt
Copy link
Author

ujjwalt commented Nov 23, 2012

Would love to see one using channels but I felt this is good enough.

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