简介

通过一层一层过滤,来得到最后的结果

代码

// build

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test basic concurrency: the classic prime sieve.
// Do not run - loops forever.

package main

// Send the sequence 2, 3, 4, ... to channel 'ch'.
func Generate(ch chan<- int) {
	for i := 2; ; i++ {
		ch <- i // Send 'i' to channel 'ch'.
	}
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
func Filter(in <-chan int, out chan<- int, prime int) {
	for {
		i := <-in // Receive value of new variable 'i' from 'in'.
		if i%prime != 0 {
			out <- i // Send 'i' to channel 'out'.
		}
	}
}

// The prime sieve: Daisy-chain Filter processes together.
func Sieve() {
	ch := make(chan int) // Create a new channel.
	go Generate(ch)      // Start Generate() as a subprocess.
	for {
		prime := <-ch
		print(prime, "\n")
		ch1 := make(chan int)
		go Filter(ch, ch1, prime)
		ch = ch1
	}
}

func main() {
	Sieve()
}

原理解释:

Generate 生成的chan 里面包含的数字是 2,3,4,5….等自然数,第一个素数

当第一个Filter(ch,prime) 从Generate 生成的数字,过滤不能被第一个整除的数字 。

以此类推,第N个prime 为不能被 N-1所有素数整除

得出每个filter 输出的第一个数为素数

以上算法原理,也可以写成:

package main

import (
	"fmt"
)

func isPrime(primes []int, num int) bool {
	for _, prime := range primes { //此处即Filter的作用
		if num%prime == 0 {
			return false
		}
	}
	return true
}

func main() {
	primes := []int{}
	for i := 2; ; i++ { //此处是Generate的作用
		if isPrime(primes, i) {
			primes = append(primes, i)
			fmt.Printf("%v: %v\n", len(primes), i)
		}
		if len(primes) > 100 {
			break
		}
	}
}
humboldt Written by:

humboldt 的趣味程序园