Introduction
In this article, we will discuss how to calculate the square root of a non-negative integer x
rounded down to the nearest integer. We will explore two different approaches to solve this problem and compare their time and space complexity.
Problem Statement
Given a non-negative integer x
, return the square root of x
rounded down to the nearest integer. The returned integer should be non-negative as well. You must not use any built-in exponent function or operator.
Algorithmic approach
Approach 1: Brute Force
The brute force approach is to check all the integers smaller than or equal to the square root of x
. We start with i=1
and increment i
until i*i > x
. Finally, we return i-1
as the result.
Approach 2: Binary Search
Another approach to solving this problem is to use binary search. We start with left=1
and right=x
. We calculate the middle-value mid=(left+right)/2
. If mid*mid > x
, we set right=mid-1
. Otherwise, we set left=mid+1
. We continue this process until left>right
. Finally, we return right
as the result.
Time Complexity
The time complexity of the brute force approach is O(sqrt(x)), and the time complexity of the binary search approach is O(log(x)).
Space Complexity
Both approaches have a constant space complexity of O(1).
Conclusion
In this article, we have discussed two different approaches to calculating the square root of a non-negative integer x
rounded down to the nearest integer. We have seen that the binary search approach is more efficient than the brute force approach.