// A concurrent solution to finding Pythagorean triplets with sum 5000 package main import "fmt" // Representation of Pythagorean triplets type Triplet [3]int // Find Pythagorean triplets starting with values from channel 'in'. // Send the triplets to channel 'out'. func FindPythTriplets(in <-chan int, out chan<- Triplet, maxsum int) { i := <-in // Receive value from 'in'. for i < maxsum { for j := i+1; i+j < maxsum; j++ { for k := j+1; i+j+k <= maxsum; k++ { if i*i + j*j == k*k { out <- Triplet{i,j,k} // Send triplet to 'out'. } } } i = <-in // Get next start value } } // Send the sequence 1, 2, 3, 4, ... to channel 'ch'. func Generate(ch chan<- int) { for i := 1; ; i++ { ch <- i // Send 'i' to channel 'ch'. } } // The main operation: create workers and receive results func main() { const sum = 5000 // the sum we are searching const numworkers = 20 // number of workers numbers := make(chan int) // create new channel with numbers go Generate(numbers) triplets := make(chan Triplet) // create new channel for results for i := 1; i <= numworkers; i++ { // create workers go FindPythTriplets(numbers, triplets, sum) } ts := Triplet{0,0,0} for ts[0]+ts[1]+ts[2] != sum { ts = <- triplets } fmt.Println(ts) } /* Execution: > time go run pythagorean.go ...with specifying used processors: > export GOMAXPROCS=1 && time go run pythagorean.go > export GOMAXPROCS=2 && time go run pythagorean.go > export GOMAXPROCS=4 && time go run pythagorean.go > export GOMAXPROCS=8 && time go run pythagorean.go Run-time (Thinkpad T14s, i7-1165G7 @ 2.8GHz, 8 processors, in seconds) with setting GOMAXPROCS= 1: 2.95 2: 1.60 4: 0.89 8: 0.86 */