Last active
February 5, 2019 17:04
-
-
Save betandr/c01fbd59b3d96eb9f728ab212545bc78 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes implemented with Go goroutines and channels
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" | |
// 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