Last active
February 27, 2018 11:52
-
-
Save kcinnu/01e056fe3a156eba1c4a01e094f960ed to your computer and use it in GitHub Desktop.
simple multithreaded pythagorean triple finder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"runtime" | |
) | |
func issqr(t int) int { | |
for i := 0; true; i++ { | |
if(i*i == t) { | |
return i | |
}else if(i*i > t){ | |
return -1 | |
} | |
} | |
return -1 | |
} | |
func filt_triples(in chan [2]int, out chan [3]int) { | |
for i := range in { | |
temp := issqr(i[0]*i[0] + i[1]*i[1]) | |
if(temp != -1) { | |
out <- [3]int{i[0], i[1], temp} | |
} | |
} | |
} | |
func sendvals(out chan [2]int) { | |
cur := [2]int{1, 1} | |
for { | |
out <- cur | |
if cur[0] >= cur[1] { | |
cur[0] = 1 | |
cur[1]++ | |
} else { | |
cur[0]++ | |
} | |
} | |
} | |
func main() { | |
nthreads := runtime.NumCPU() | |
var ngr int | |
if nthreads < 2 { | |
ngr = 1 | |
} else { | |
ngr = nthreads - 2 | |
} | |
vals := make(chan [2]int, 0x100) | |
triples := make(chan [3]int, 0x100) | |
go sendvals(vals) | |
for i := 0; i < ngr; i++ { | |
go filt_triples(vals, triples) | |
} | |
for i := range triples { | |
fmt.Println(i[0], i[1], i[2]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment