Link Address: https://leetcode.com/problems/sqrtx/
The problem is to ask for the square root of a number.
I'm here to offer three ways
1: Everyone knows that the square root must be between [1,X/2], so from 1 cycles to X/2, but when X=1 is passed, not a good method and will tle
Class Solution { //tle and imprecise public: int sqrt (int x) { int t = X/2; for (int i = 0; i<= t; i++) if ((i * i) = = x) return i; return-1; }};
2: Dichotomy
We know that the time complexity required for the dichotomy is O (LgN), so that it does not time out.
Class Solution {public: int sqrt (int x) { double begin = 0; Double end = x; double result = 1; Double mid = 1; while (ABS (result-x) > 0.000001) { mid = (begin+end)/2; result = Mid*mid; if (Result > x) //Two-point range end = mid; else begin = Mid; } return (int) mid; }};
3: Newton Iterative method
NewtonIterative method(Newton ' s method) also known asNewton-Raphson (Kristinn) methods (Newton-raphson method), it isNewtonpresented in 17th century as aRealDomain andPluralon the domainApproximate solution equation the method. set R yes
the root, selectas the initial approximation of R, over PointdoCurvethe equation for the tangent l,l isto find the horizontal axis of the intersection of L and X axis, called X
1is an approximate value of R. Over DotMake a curvetangent and the horizontal axis of the x-axis intersection, saidtwo approximate values for R. Repeat the above process to get a sequence of approximate values of R, where,called R.The second approximation, the above-namedNewton's iterative formula. The following code cur = pre/2 + x/(2*pre) is the result of the simplification calculation. Here's f (x) = X^2-n
* Newton Iterative Method */class Solution {public: int sqrt (int x) { double pre = 0; Double cur = x; Starting at x starting from X/2 will cause 1 to not meet x (n+1) = Xn-f ' (xn)/f (xn) while (ABS (CUR-PRE) > 0.000001) { pre = cur;
cur = (PRE/2 + x/(2*pre)); } return int (cur); }};
LeetCode69 Sqrt (x)