diff --git a/problems/sqrtx/sqrtx.go b/problems/sqrtx/sqrtx.go index 02a4b62f2..de05f0d02 100644 --- a/problems/sqrtx/sqrtx.go +++ b/problems/sqrtx/sqrtx.go @@ -1 +1,12 @@ package sqrtx + +func mySqrt(x int) int { + if x < 2 { + return x + } + r := x / 2 + for r > x/r { + r = (r + x/r) / 2 + } + return r +} diff --git a/problems/sqrtx/sqrtx_test.go b/problems/sqrtx/sqrtx_test.go index 02a4b62f2..59da5aac6 100644 --- a/problems/sqrtx/sqrtx_test.go +++ b/problems/sqrtx/sqrtx_test.go @@ -1 +1,35 @@ package sqrtx + +import "testing" + +type caseType struct { + input int + expected int +} + +func TestMySqrt(t *testing.T) { + tests := [...]caseType{ + { + input: 4, + expected: 2, + }, + { + input: 8, + expected: 2, + }, + { + input: 0, + expected: 0, + }, + { + input: 1, + expected: 1, + }, + } + for _, tc := range tests { + output := mySqrt(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}