Skip to content

Instantly share code, notes, and snippets.

@betandr
Last active February 5, 2019 17:04
Show Gist options
  • Save betandr/c01fbd59b3d96eb9f728ab212545bc78 to your computer and use it in GitHub Desktop.
Save betandr/c01fbd59b3d96eb9f728ab212545bc78 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes implemented with Go goroutines and channels
package main
import "fmt"
// Generate primes and send them to channel `ch`
func Generate(ch chan<- int) {
for i := 2; ; i++ {
ch <- i
}
}
// Filter primes through the sieve from the `src` to `dst` channels
func Filter(src <-chan int, dst chan<- int, prime int) {
for i := range src {
if i%prime != 0 {
dst <- i
}
}
}
func main() {
src := make(chan int)
go Generate(src)
for i := 0; i < 100; i++ {
prime := <-src
fmt.Printf("%d, ", prime)
dst := make(chan int)
go Filter(src, dst, prime)
src = dst
}
fmt.Println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment