Created
July 6, 2014 08:20
-
-
Save chenyukang/68edd87ad56e09c47214 to your computer and use it in GitHub Desktop.
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" | |
// 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