sieve2.go 848 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "fmt"
  7. )
  8. // Send the sequence 2, 3, 4, ... to returned channel
  9. func generate() chan int {
  10. ch := make(chan int)
  11. go func() {
  12. for i := 2; ; i++ {
  13. ch <- i
  14. }
  15. }()
  16. return ch
  17. }
  18. // Filter out input values divisible by 'prime', send rest to returned channel
  19. func filter(in chan int, prime int) chan int {
  20. out := make(chan int)
  21. go func() {
  22. for {
  23. if i := <-in; i%prime != 0 {
  24. out <- i
  25. }
  26. }
  27. }()
  28. return out
  29. }
  30. func sieve() chan int {
  31. out := make(chan int)
  32. go func() {
  33. ch := generate()
  34. for {
  35. prime := <-ch
  36. ch = filter(ch, prime)
  37. out <- prime
  38. }
  39. }()
  40. return out
  41. }
  42. func main() {
  43. primes := sieve()
  44. for {
  45. fmt.Println(<-primes)
  46. }
  47. }