Skip to content

Instantly share code, notes, and snippets.

@phagenlocher
Created August 15, 2016 21:28
Show Gist options
  • Select an option

  • Save phagenlocher/5982b3b0119638d0443fdd96b2a1270b to your computer and use it in GitHub Desktop.

Select an option

Save phagenlocher/5982b3b0119638d0443fdd96b2a1270b to your computer and use it in GitHub Desktop.
Generating prime numbers with go routines
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func generate_prime(min int, max int, result chan int) {
MainLoop:
// Generate number between min and max
x := (rand.Int() % (max - min + 1)) + min
// Test for prime
for i := 2; i <= int(math.Sqrt(float64(x))); i++ {
if x%i == 0 {
// If its divisible, go to function start
goto MainLoop
}
}
// Send result via chan
result <- x
}
func main() {
// Number of routines to start
num_routines := 100
// Buffered chan to get results on routines
result := make(chan int, num_routines)
// Seeding RNG with current time
rand.Seed(time.Now().Unix())
// Starting routines
for i := 0; i < num_routines; i++ {
go generate_prime(100000, 1000000000, result)
}
// Waiting for routines to finish
results := 0
for results < cap(result) {
fmt.Println(<-result)
results++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment