Sqrt(x) Algorithm

The Sqrt(x) Algorithm, also known as the square root algorithm, is a method used to compute the square root of a given number x. The algorithm is based on the mathematical property that the square root of a number x can be represented as the number y such that y * y = x. There are various methods to compute the square root, including the Babylonian method, Newton-Raphson method, and the binary search method. These algorithms can be implemented in various programming languages and are commonly used in mathematical computations, scientific research, and engineering applications. One of the most popular square root algorithms is the Babylonian method, which is an iterative method that can be easily implemented in a programming language. The algorithm starts with an initial guess of the square root and refines this guess through successive iterations until the desired level of precision is reached. The iterative formula for the Babylonian method is y = 0.5 * (y + x/y), where y is the current guess and x is the number whose square root is being computed. The algorithm converges quickly, typically requiring only a few iterations to achieve high precision. Other methods such as the Newton-Raphson method and the binary search method are also used to compute square roots, depending on the specific requirements of a given application.
class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        long long lf = 0;
        long long rt = x;
        while (lf <= rt) {
            long long m = (lf + rt) >> 1;
            long long sq = m * m;
            if (sq == (long long)x)
                return m;
            else if (sq < (long long)x)
                lf = m + 1;
            else 
                rt = m - 1;
        }
        return (int)rt;
    }
};

LANGUAGE:

DARK MODE: