The Go language method for generating prime Numbers

  • 2020-05-27 05:48:51
  • OfStack

This article illustrates an example of how the Go language generates primes. Share with you for your reference. The specific implementation method is as follows:

package main
// generate 2, 3, 4, ... to channel 'ch' In the .
func Generate(ch chan<- int) {
    for i := 2; ; i++ {
        ch <- i  // Send 'i' to channel 'ch'.
    }
}
// Copy the value from the pipe 'in' to channel 'out',
// Remove the divisible number 'prime'.
func Filter(in <-chan int, out chan<- int, prime int) {
    for {
        i := <-in    // Receives the value 'in'.
        if i%prime != 0 {
            out <- i // The incoming 'i' to 'out'.
        }
    }
}
func main() {
    ch := make(chan int)    // Create a newchannel.
    go Generate(ch) // Launch Generate goroutine.
    for i := 0; i < 10; i++ {
        prime := <-ch
        print(prime, "\n")
        ch1 := make(chan int)
        go Filter(ch, ch1, prime)
        ch = ch1
    }
}

I hope this article has been helpful to your programming of Go language.


Related articles: