LeetCode Online Judge 题目C# 练习 - Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
1 public static int Sqrt(int x) 2 { 3 if (x == 0) return 0; 4 5 ulong x2 = (ulong)x; 6 ulong l = 0; 7 ulong r = (ulong)x; 8 ulong mid; 9 10 while (l <= r) 11 { 12 mid = l + (r - l) / 2; 13 14 //if Square(mid) < x < Square(mid + 1) 15 if (mid * mid == x2 || (x2 > mid * mid && x2 < (mid + 1) * (mid + 1))) 16 return (int)mid; 17 else if (mid * mid > x2) 18 r = mid - 1; 19 else 20 l = mid + 1; 21 } 22 23 return -1; 24 }
代码分析:
二分法找平方根。
复习一下牛顿法求平方根。
xk+1 = (xk + n / xk) / 2 (X0 = 1)
C code:
1 float Sqrt(int n) 2 { 3 float x = 1; 4 //收敛1000次,越多越准 5 for(int i = 1; i <= 1000; i++) 6 { 7 x = (x + n / 2) / 2; 8 } 9 10 return x; 11 }