HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Pythagorean Triple Generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythagoreantriplegenerator

Problem

I'm just playing about with Go, and am trying to solve some project euler problems to get used to it.

I've created a generator function for Pythagorean triples, using a channel which returns a set of 3 integers for the sides, like so (HCF implements Euclid's algorithm for finding greatest common divisor or highest common factor in this part of the world):

package main
import "fmt"

func HCF(a, b int) int {
    if a % b == 0 {
        return b
    } else {
        return HCF(b, a%b)
    }
}

func PythagTriple() chan [3]int {

    ch := make(chan [3]int)

    go func() {
        for m := 2; ; m++ {
            for n := m%2 + 1; n < m; n += 2 {
                if HCF(m, n) == 1 {
                    var triple [3]int
                    triple[0] = m*m - n*n
                    triple[1] = 2 * m * n
                    triple[2] = m*m + n*n
                    ch <- triple
                }
            }
        }
    }()

    return ch
}

func main() {

    ch := PythagTriple()
    for i := 0; i < 10; i++ {
        fmt.Println(<- ch)
    }
}


Questions:

  • Do I need to do anything with the channel, or will it close and clean up when it goes out of scope?



  • Is there a better way of creating a quick array than how I've done it?



  • Is this idiomatic Go, or am I barking up the wrong tree entirely? I've just started and am not sure if I'm doing it right!



Don't worry too much about efficiency of the algorithm; I'm not too concerned about speed at this point.

Solution

Not a Go expert but I think you should be able to define your array of values as you declare it :

triple := [...]int{m*m - n*n, 2 * m * n, m*m + n*n}


Source

Code Snippets

triple := [...]int{m*m - n*n, 2 * m * n, m*m + n*n}

Context

StackExchange Code Review Q#82990, answer score: 2

Revisions (0)

No revisions yet.