Skip to content

Commit

Permalink
binary search to sqrt. go implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed Apr 24, 2019
1 parent 6463cab commit 32a40df
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 69. Sqrt(x)/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import "fmt"

func mySqrt2(x int) int {
x0 := 1
var tem int
for {
tem = x0
x0 = (x0 + x/x0) / 2
fmt.Println(x0)
if tem <= x0 {
break
}

}
return x0

}

func mySqrt(x int) int {
if x == 0 {
return 0
}
left, right := 1, x
var mid int
for left+1 < right {
mid = (left + right) / 2
if mid*mid > x {
right = mid
fmt.Println("right:", right)
} else {
left = mid
fmt.Println("left:", left)
}
}
return left
}

func main() {
fmt.Println(mySqrt(4))
}

0 comments on commit 32a40df

Please sign in to comment.