Created
March 13, 2021 23:46
-
-
Save maksadbek/248e61d5aaed4992df5ab8c0e333d88f to your computer and use it in GitHub Desktop.
Calculate primes using Doug McIlroy's idea: http://swtch.com/~rsc/thread/
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 "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