Skip to content

Commit 5bac132

Browse files
committed
Add: Sqrt(x)
1 parent 040a7cf commit 5bac132

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

problems/sqrtx/sqrtx.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,12 @@
11
package sqrtx
2+
3+
func mySqrt(x int) int {
4+
if x < 2 {
5+
return x
6+
}
7+
r := x / 2
8+
for r > x/r {
9+
r = (r + x/r) / 2
10+
}
11+
return r
12+
}

problems/sqrtx/sqrtx_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package sqrtx
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input int
7+
expected int
8+
}
9+
10+
func TestMySqrt(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: 4,
14+
expected: 2,
15+
},
16+
{
17+
input: 8,
18+
expected: 2,
19+
},
20+
{
21+
input: 0,
22+
expected: 0,
23+
},
24+
{
25+
input: 1,
26+
expected: 1,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := mySqrt(tc.input)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)