Tutorialspoint
Problem
Solution
Submissions

Sqrt(x) Function

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to compute and return the square root of a non-negative integer x. Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. You must implement this without using any built-in exponent function or operator like sqrt().

Example 1
  • Input: x = 4
  • Output: 2
  • Explanation:
    • We need to find the square root of 4.
    • The square root of 4 is 2.0.
    • Since we need to return only the integer part, we get 2.
    • Therefore, the output is 2.
Example 2
  • Input: x = 8
  • Output: 2
  • Explanation:
    • We need to find the square root of 8.
    • The square root of 8 is approximately 2.82842...
    • Since we need to return only the integer part, we get 2.
    • Therefore, the output is 2.
Constraints
  • 0 <= x <= 2^31 - 1
  • You must not use any built-in library function like sqrt()
  • Time Complexity: O(log x)
  • Space Complexity: O(1)
NumberZomatoSwiggy
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 0 to x
  • For each middle value, check if its square is less than or equal to x
  • If the square is greater than x, search in the left half
  • If the square is less than x, search in the right half
  • Be careful about potential integer overflow when calculating squares

Steps to solve by this approach:

Step 1: Handle edge cases where x is 0 or 1, as the square root is the number itself.

Step 2: Set up a binary search with left boundary at 1 and right boundary at x.
Step 3: Calculate the middle point as mid = left + (right - left) / 2 to avoid potential overflow.
Step 4: Calculate the square of the middle point as square = mid * mid, using long data type to avoid overflow. Step 5: If square equals x, we found the exact square root and return it. Step 6: If square is less than x, search in the right half (left = mid + 1) and update result to mid (this could be our answer if x has no perfect square root). Step 7: If square is greater than x, search in the left half (right = mid - 1).

Submitted Code :