# x 的平方根

CancerTiN · · 1073 次点击 · · 开始浏览

Golang解决：

``````package main

import "fmt"

func binaryFind(x, l, r int) (t int) {
m := (l + r + 1) >> 1
if x < m*m {
t = binaryFind(x, l, m-1)
} else if (m+1)*(m+1) < x {
t = binaryFind(x, m, r)
} else {
t = m
if (m+1)*(m+1) == x {
t++
}
}
return
}

func mySqrt(x int) int {
return binaryFind(x, 0, x>>1+1)
}

func main() {
for _, x := range []int{4, 8, 9, 8192, 6, 2147483647} {
fmt.Println(x, mySqrt(x))
}
}
``````

``````4 2
8 2
9 3
8192 90
6 2
2147483647 46340
``````

• x = 8; y = x>>1
• x = 8; y = x/2

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

Golang解决：

``````package main

import "fmt"

func binaryFind(x, l, r int) (t int) {
m := (l + r + 1) >> 1
if x < m*m {
t = binaryFind(x, l, m-1)
} else if (m+1)*(m+1) < x {
t = binaryFind(x, m, r)
} else {
t = m
if (m+1)*(m+1) == x {
t++
}
}
return
}

func mySqrt(x int) int {
return binaryFind(x, 0, x>>1+1)
}

func main() {
for _, x := range []int{4, 8, 9, 8192, 6, 2147483647} {
fmt.Println(x, mySqrt(x))
}
}
``````

``````4 2
8 2
9 3
8192 90
6 2
2147483647 46340
``````

• x = 8; y = x>>1
• x = 8; y = x/2