Tutorialspoint
Problem
Solution
Submissions

Square Root Function

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 5

Write a Java program to compute and return the square root of a non-negative integer x, rounded down to the nearest integer (the floor value). You are not allowed to use any built-in square root function or operator.

Example 1
  • Input: x = 4
  • Output: 2
  • Explanation:
    • Step 1: Use binary search approach to find the square root of the integer.
    • Step 2: The search range is initially from 1 to x.
    • Step 3: For x = 4, the middle value is 2.
    • Step 4: Since 2 * 2 = 4, which equals x, return 2 as the answer.
Example 2
  • Input: x = 8
  • Output: 2
  • Explanation:
    • Step 1: Use binary search approach to find the square root of the integer.
    • Step 2: The search range is initially from 1 to 8.
    • Step 3: For x = 8, we need to find the largest integer whose square is less than or equal to 8.
    • Step 4: Check 2: 2 * 2 = 4, which is less than 8.
    • Step 5: Check 3: 3 * 3 = 9, which is greater than 8.
    • Step 6: Return 2 as the floor value of the square root of 8.
Constraints
  • 0 ≤ x ≤ 2^31 - 1
  • You cannot use any built-in library function like Math.sqrt()
  • Time Complexity: O(log x)
  • Space Complexity: O(1)
NumberGoldman SachsSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search to find the square root
  • Start with a search range from 1 to x
  • For each mid value, check if mid * mid is less than or equal to x
  • Be careful with integer overflow when calculating mid * mid
  • Return the largest integer whose square is less than or equal to x

Steps to solve by this approach:

 Step 1: Handle the edge case where x is 0, return 0.
 Step 2: Use binary search with left = 1 and right = x to find the square root.
 Step 3: For each middle point (mid), compute mid * mid and compare it with x.
 Step 4: Use long type to avoid integer overflow when calculating mid * mid.
 Step 5: If mid * mid equals x, return mid as the exact square root.
 Step 6: If mid * mid is less than x, update left = mid + 1 and save mid as a potential result.
 Step 7: If mid * mid is greater than x, update right = mid - 1.

Submitted Code :