Initial upload
This commit is contained in:
39
go/pythagorean-triplet/pythagorean_triplet.go
Normal file
39
go/pythagorean-triplet/pythagorean_triplet.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package pythagorean
|
||||
|
||||
import "math"
|
||||
|
||||
type Triplet [3]int
|
||||
|
||||
func isTriplet(a, b, c int) bool {
|
||||
return a*a + b*b == c*c && a < b && b < c
|
||||
}
|
||||
|
||||
func Range(min, max int) []Triplet {
|
||||
var triplets = []Triplet{}
|
||||
for c := min; c <= max; c++ {
|
||||
for b := min; b <= c - 1; b++ {
|
||||
a := int(math.Sqrt(float64(c*c - b*b)))
|
||||
|
||||
if isTriplet(a, b, c) && a >= min {
|
||||
triplets = append(triplets, Triplet{a,b,c})
|
||||
}
|
||||
}
|
||||
}
|
||||
return triplets
|
||||
}
|
||||
|
||||
func Sum(p int) []Triplet {
|
||||
temp_triplets := Range(1, p / 2)
|
||||
triplets := make([]Triplet, 0, len(temp_triplets))
|
||||
|
||||
for _, triplet := range temp_triplets {
|
||||
if triplet[0] + triplet[1] + triplet[2] == p {
|
||||
triplets = append(triplets, triplet)
|
||||
}
|
||||
}
|
||||
// Reverse slice..
|
||||
for i, j := 0, len(triplets)-1; i < j; i, j = i+1, j-1 {
|
||||
triplets[i], triplets[j] = triplets[j], triplets[i]
|
||||
}
|
||||
return triplets
|
||||
}
|
||||
Reference in New Issue
Block a user