Last active
October 13, 2015 03:57
-
-
Save ujjwalt/4135197 to your computer and use it in GitHub Desktop.
A concurrent implementation of Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would love to see one using channels but I felt this is good enough.