1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| func sqrt(x float64) float64 { l, r := float64(1), x mid := (l + r) / 2 for mid-l > 0.000001 { if mid*mid > x { r = mid } else { l = mid } mid = (l + r) / 2 } return mid }
func mySqrt(x float64) float64 { l, r := float64(0), x ans := -1.0 for l <= r { mid := l + (r-l)/2 if mid*mid > x { r = mid - 1 } else { ans = mid l = mid + 1 } } return ans }
|