fork download
  1. package main
  2. import "fmt"
  3.  
  4. // Send the sequence 2, 3, 4, ... to channel 'ch'
  5. func Generate(ch chan<- int) {
  6. for i := 2; ; i++ {
  7. ch <- i // Send 'i' to channel 'ch'
  8. }
  9. }
  10.  
  11. // Copy the values from channel 'in' to channel 'out',
  12. // removing the multiples of 'prime'.
  13. // 'in' assumed to send increasing numbers
  14. func Filter(in <-chan int, out chan<- int, prime int) {
  15. m := prime + prime
  16. for {
  17. i := <- in // Receive value from 'in'
  18. for i > m {
  19. m = m + prime
  20. }
  21. if i < m {
  22. out <- i // Send 'i' to 'out'
  23. }
  24. }
  25. }
  26.  
  27. // The prime sieve: Daisy-chain Filter processes
  28. func Sieve(out chan<- int) {
  29. ch := make(chan int) // Create a new channel
  30. go Generate(ch) // Launch Generate goroutine
  31. for {
  32. prime := <-ch
  33. out <- prime
  34. ch1 := make(chan int)
  35. go Filter(ch, ch1, prime)
  36. ch = ch1
  37. }
  38. }
  39.  
  40. func main() {
  41. ch := make(chan int) // Create a new channel
  42. go Sieve(ch) // Launch Sieve goroutine
  43. m := 3000
  44. for i := 0; i < m; i++ {
  45. prime := <-ch
  46. if i >= (m-5) {
  47. fmt.Printf("%4d ", prime)
  48. //if (i+1)%10==0 {
  49. // fmt.Println("")
  50. //}
  51. }
  52. }
  53. }
  54. /*
  55. 3000: time: 4.02 memory: 789504 signal:0 ---- n^2.1 ----
  56. 27409 27427 27431 27437 27449
  57.  
  58. 2000: time: 1.75 memory: 789504 signal:0 ---- n^2.1 ----
  59. 17359 17377 17383 17387 17389
  60.  
  61. 1000: time: 0.39 memory: 789504 signal:0
  62. 7879 7883 7901 7907 7919
  63. */
Success #stdin #stdout 4.02s 789504KB
stdin
Standard input is empty
stdout
27409 27427 27431 27437 27449