Sqrt(x)

Updated on 02 July, 2025
Sqrt(x) header image

Problem Statement

In this problem, we are tasked with finding the square root of a non-negative integer x and returning the integer part of the square root. The challenge is to implement this functionality without using any built-in exponent functions or operators, such as pow(x, 0.5) in C++ or x ** 0.5 in Python. The output must always be a non-negative integer, and it should effectively represent the floor value of the square root of x. This involves returning the largest integer y such that y * y <= x.

Examples

Example 1

Input:

x = 4

Output:

2

Explanation:

The square root of 4 is 2, so we return 2.

Example 2

Input:

x = 8

Output:

2

Explanation:

The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints

  • 0 <= x <= 231 - 1

Approach and Intuition

To solve this problem without using any built-in square root functions, we can leverage several classical numerical methods that are effective for finding square roots. Here’s a straightforward approach using binary search due to its efficiency in handling large numbers especially given the constraint 0 <= x <= 231 - 1.

  1. Initial Setup: If x is 0 or 1, the square root is x itself. This can be immediately returned.

  2. Binary Search Method:

    • Start with two pointers, left initialized to 1 and right initialized to x.
    • Continuously refine the search space based on the middle element mid calculated as (left + right) / 2.
    • Check the square of mid (i.e., mid * mid):
      • If mid * mid equals x, mid is the exact square root and can be returned.
      • If mid * mid is less than x, update left to mid + 1 to consider higher half for potential square roots.
      • If mid * mid is greater than x, update right to mid - 1 to consider lower half.
    • Continue this process until left exceeds right.
    • Return right which will hold the floor of the square root due to the properties of integer division in programming (rounding down).

Example Walkthroughs:

Example 1:

  • Input: x = 4
  • From our method:
    • Start with left = 1 and right = 4.
    • Calculate the mid, which would modify right to converge to the correct floor of the square root.
    • Eventually, we would find that mid * mid becomes equal to x, making mid our answer, which is 2.

Example 2:

  • Input: x = 8
  • Here, the square root of 8 is approximately 2.83. Following similar steps as Example 1, our binary search will close in on the integer part:
    • The binary search adjustments would lead us to converge on 2 as the right value when left surpasses right, returning 2 as the largest integer satisfying y * y <= x.
  • The output remains the same because integers naturally discard their decimal parts in mathematical operations without explicit rounding.

This binary search method ensures that we operate in logarithmic time complexity, making it efficient even for the upper limits of the constraints.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int calculateSqrt(int num) {
        if (num < 2) return num;
        double t0 = num;
        double t1 = (t0 + num / t0) / 2.0;
        while (abs(t0 - t1) >= 1) {
            t0 = t1;
            t1 = (t0 + num / t0) / 2.0;
        }
        return (int)t1;
    }
};

The provided C++ code defines a solution to calculate the integer square root of a given number, num. Implementing a method within a Solution class called calculateSqrt, the code effectively approximates the square root without using any direct square root function.

  • In the method, a condition first checks if the input num is less than 2. If true, it immediately returns the input as the square root of any number less than 2 is the number itself.
  • A more interesting aspect of the code lies in its use of a variation of Newton's method for iteratively converging to the square root:
    • Initialize t0 with the value of num and t1 follows Newton's formula for square root approximation: (t0 + num / t0) / 2.0.
    • Using a while loop, the method iteratively improves the estimate t1 until the changes between subsequent iterations are small enough (less than 1 in this implementation).
    • The loop updates t0 to t1 and recalculates t1 using the same formula in each iteration.
  • It finally converts the floating-point result to an integer and returns it, providing the largest integer less than or equal to the true square root.

This solution is efficient for large numbers as it reduces the dependence on successive approximations and utilizes mathematical principles to achieve accuracy in the integer domain.

java
class Solution {
    public int calculateSqrt(int number) {
        if (number < 2) return number;
    
        double lastGuess = number;
        double newGuess = (lastGuess + number / lastGuess) / 2.0;
        while (Math.abs(lastGuess - newGuess) >= 1) {
            lastGuess = newGuess;
            newGuess = (lastGuess + number / lastGuess) / 2.0;
        }
    
        return (int) newGuess;
    }
}

This Java solution efficiently finds the integer square root of a given number using a method resembling the Newton-Raphson approach. Follow these steps to understand how the function calculateSqrt works:

  1. Check if the input number is less than 2. If so, return the number itself since the square root of 0 or 1 is the number itself.

  2. Initialize lastGuess to the number and newGuess to the average of lastGuess and the division of the number by lastGuess. This setup starts the iterative approach to approximate the square root.

  3. Use a loop to repeatedly refine newGuess. Inside the loop:

    • Update lastGuess to the current newGuess.
    • Calculate a new newGuess as the average of lastGuess and the division of the number by lastGuess.
    • Continue this process until the absolute difference between lastGuess and newGuess is less than one, ensuring convergence to the closest integer square root value.
  4. Once the loop ends, cast newGuess to an integer and return it. This value is the integer closest to the square root of the provided number not exceeding the actual square root.

This approach typically converges very quickly to the correct result, making it a highly efficient algorithm for square root calculation.

c
int calcSqrt(int number) {
    if (number < 2) return number;
    double estimate = number;
    double nextEstimate = (estimate + number / estimate) / 2.0;
    while (fabs(estimate - nextEstimate) >= 1) {
        estimate = nextEstimate;
        nextEstimate = (estimate + number / estimate) / 2.0;
    }
    return (int)nextEstimate;
}

The problem focuses on determining the square root of an integer in C using a numerical method to approximate it. The core function calcSqrt efficiently finds the square root of a given non-negative integer number.

  • Start by checking if the number is less than 2. If true, return the number itself as the square root of either 0 or 1 is the number itself.
  • Initialize estimate to the input number, which acts as the initial guess for the square root.
  • Calculate the next estimate for the square root using the iteration formula (estimate + number / estimate) / 2.0. This formula continually refines the guess based on the previous estimate.
  • Use a loop to apply the formula continuously until the change between successive estimates is less than 1, which signifies that successive estimates are close enough for an integer approximation.
  • Return the floor of the nextEstimate which is the integer part of the computed square root.
js
var calculateSqrt = function (value) {
    if (value < 2) return value;
    let current = value;
    let next = (current + value / current) / 2.0;
    while (Math.abs(current - next) >= 1) {
        current = next;
        next = (current + value / current) / 2.0;
    }
    return Math.floor(next);
};

The provided JavaScript function, calculateSqrt, efficiently calculates the integer part of the square root of a given non-negative integer (value) using the Newton-Raphson method, a powerful formula used to find successively better approximations to the roots of a real-valued function.

Summary of the Code Execution:

  1. First, check if the input value is less than 2. If true, return the value itself, as both 0 and 1 are their own square roots.
  2. Initialize a variable, current, with the value of the input. This variable will store the current approximation of the square root.
  3. Calculate an initial approximation called next using the Newton-Raphson formula: ( \text{next} = \frac{\text{current} + \frac{\text{value}}{\text{current}}}{2} ).
  4. Enter a loop that continues until the absolute difference between current and next is less than 1. This loop refines the approximate value of the square root:
    • Update current to the value of next.
    • Recalculate next using the updated current.
  5. Once the loop ends (mean the difference is less than 1), the approximation of the square root is almost accurate but might still be fractional. Use Math.floor(next) to convert this to the nearest lower integer.

This loop method ensures precision by incrementally getting closer to the true square root and then using the floor function to ensure the result is the largest integer less than or equal to the actual square root. This solution is particularly efficient for large values due to its rapid convergence compared to other methods such as exhaustive search or binary search methods for large integers.

python
class Solution:
    def computeSqrt(self, num: int) -> int:
        if num < 2:
            return num
    
        value1 = num
        value2 = (value1 + num / value1) / 2
        while abs(value1 - value2) >= 1:
            value1 = value2
            value2 = (value1 + num / value1) / 2
    
        return int(value2)

The solution provided calculates the integer square root of a number using the Newton-Raphson method, which converges quickly to a function's root. The main steps involve:

  1. Check if the input number is less than 2; if so, return the number itself.
  2. Initialize value1 with the input number and calculate an initial approximation value2 as (value1 + num / value1) / 2.
  3. Use a while loop to repeatedly refine the approximation. The loop runs until the absolute difference between value1 and value2 is less than 1.
  4. Within the loop, update value1 to value2, and then recalculate value2 using the formula (value1 + num / value1) / 2.
  5. Once the loop exits (i.e., the successive approximations are sufficiently close), return the integer part of value2.

This implementation efficiently finds the largest integer less than or equal to the square root of num, ensuring precision by iterative approximation.

Comments

No comments yet.