Skip to content

Instantly share code, notes, and snippets.

@chenyukang
Created July 6, 2014 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenyukang/68edd87ad56e09c47214 to your computer and use it in GitHub Desktop.
Save chenyukang/68edd87ad56e09c47214 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// send the sequence of 2, 3, 4, .... to returned channel
func generate() chan int {
ch := make(chan int)
go func() {
for i := 2; ; i++ {
ch <- i
}
}()
return ch
}
// Filter out the numbers which is not prime
func filter(in chan int, prime int) chan int {
out := make(chan int)
go func() {
for {
if i := <-in; i%prime != 0 {
out <- i
}
}
}()
return out
}
// generate all the prime numbers using sieve algorithm
func sieve() chan int {
out := make(chan int)
go func() {
ch := generate()
for {
prime := <-ch
ch = filter(ch, prime)
out <- prime
}
}()
return out
}
func main() {
primes := sieve()
for x := range primes {
fmt.Println(x)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment