Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created March 13, 2021 23:46
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 maksadbek/248e61d5aaed4992df5ab8c0e333d88f to your computer and use it in GitHub Desktop.
Save maksadbek/248e61d5aaed4992df5ab8c0e333d88f to your computer and use it in GitHub Desktop.
Calculate primes using Doug McIlroy's idea: http://swtch.com/~rsc/thread/
package main
import "sync"
func primes() {
var recur func(ch chan int)
wg := sync.WaitGroup{}
recur = func(ch chan int) {
p := <-ch
newch := make(chan int)
println(p)
wg.Add(1)
go recur(newch)
for n := range ch {
if n%p != 0 {
newch <- n
}
}
close(newch)
wg.Done()
}
ch := make(chan int)
go recur(ch)
for i := 3; i < 135; i++ {
ch <- i
}
close(ch)
wg.Wait()
}
func main() {
primes()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment