
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.
- We need to find the square root of 4.
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.
- We need to find the square root of 8.
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)
Editorial
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. |
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