OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [gcc/] [testsuite/] [go.test/] [test/] [chan/] [sieve1.go] - Blame information for rev 700

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 700 jeremybenn
// $G $D/$F.go && $L $F.$A && ./$A.out
2
 
3
// Copyright 2009 The Go Authors. All rights reserved.
4
// Use of this source code is governed by a BSD-style
5
// license that can be found in the LICENSE file.
6
 
7
// Generate primes up to 100 using channels, checking the results.
8
// This sieve consists of a linear chain of divisibility filters,
9
// equivalent to trial-dividing each n by all primes p ≤ n.
10
 
11
package main
12
 
13
// Send the sequence 2, 3, 4, ... to channel 'ch'.
14
func Generate(ch chan<- int) {
15
        for i := 2; ; i++ {
16
                ch <- i // Send 'i' to channel 'ch'.
17
        }
18
}
19
 
20
// Copy the values from channel 'in' to channel 'out',
21
// removing those divisible by 'prime'.
22
func Filter(in <-chan int, out chan<- int, prime int) {
23
        for i := range in { // Loop over values received from 'in'.
24
                if i%prime != 0 {
25
                        out <- i // Send 'i' to channel 'out'.
26
                }
27
        }
28
}
29
 
30
// The prime sieve: Daisy-chain Filter processes together.
31
func Sieve(primes chan<- int) {
32
        ch := make(chan int) // Create a new channel.
33
        go Generate(ch)      // Start Generate() as a subprocess.
34
        for {
35
                // Note that ch is different on each iteration.
36
                prime := <-ch
37
                primes <- prime
38
                ch1 := make(chan int)
39
                go Filter(ch, ch1, prime)
40
                ch = ch1
41
        }
42
}
43
 
44
func main() {
45
        primes := make(chan int)
46
        go Sieve(primes)
47
        a := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
48
        for i := 0; i < len(a); i++ {
49
                if x := <-primes; x != a[i] {
50
                        println(x, " != ", a[i])
51
                        panic("fail")
52
                }
53
        }
54
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.