From f4a18fb4ed80e03b3595b17edb90af39be9e1b2e Mon Sep 17 00:00:00 2001 From: VicRen Date: Tue, 10 Nov 2020 08:55:35 +0800 Subject: [PATCH] 39: integer right triangles --- 39_integer_right_triangles/main.go | 34 +++++++++++++++++++++++++ 39_integer_right_triangles/main_test.go | 30 ++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 39_integer_right_triangles/main.go create mode 100644 39_integer_right_triangles/main_test.go diff --git a/39_integer_right_triangles/main.go b/39_integer_right_triangles/main.go new file mode 100644 index 0000000..cc42ce2 --- /dev/null +++ b/39_integer_right_triangles/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + max := 0 + fp := 0 + for p := 0; p <= 1000; p++ { + n := len(findSolutionsFor(p)) + if n > max { + max = n + fp = p + } + } + fmt.Println("max:", max, "fp", fp) +} + +func findSolutionsFor(p int) [][]int { + // a+b+c=p, a^2+b^2=c^2, a+b>c, c>a, c>b + var ret [][]int + for a := 0; a < p/2; a++ { + for b := 0; b < a; b++ { + cf := math.Sqrt(float64(a*a + b*b)) + c := int(cf) + if cf-float64(c) == 0 && a+b+c == p { + ret = append(ret, []int{b, a, c}) + } + } + } + return ret +} diff --git a/39_integer_right_triangles/main_test.go b/39_integer_right_triangles/main_test.go new file mode 100644 index 0000000..4a9795d --- /dev/null +++ b/39_integer_right_triangles/main_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test_findSolutionsFor(t *testing.T) { + type args struct { + n int + } + tests := []struct { + name string + args args + want [][]int + }{ + { + "120", + args{120}, + [][]int{{30, 40, 50}, {24, 45, 51}, {20, 48, 52}}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := findSolutionsFor(tt.args.n); !reflect.DeepEqual(got, tt.want) { + t.Errorf("findSolutionsFor() = %v, want %v", got, tt.want) + } + }) + } +}