Square root of a number

Given an integer n, find the square root of n. If n is not a perfect square, then return the floor value.

Floor value of any number is the greatest Integer which is less than or equal to that number

Examples:

Input: n = 5
Output: 2
Explanation: Since, 5 is not a perfect square, floor of square_root of 5 is 2.
Input: n = 4
Output: 2
Explanation: Since, 4 is a perfect square, so its square root is 2.

Expected Time Complexity: O(logn)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ n ≤ 107


Approach 01:

class Solution {
  public:
    long long int floorSqrt(long long int n) {
        return floor(pow(n,0.5));
    }
};
class Solution:
    def floorSqrt(self, n): 
        return int(n**(1/2))

Time Complexity

  • Function: long long int floorSqrt(long long int n):

    The function calculates the square root of n using the pow function, which computes the power of a number. The pow function generally operates in \( O(\log k) \) time where \( k \) is the exponent, but for the specific case of computing square roots, it is often considered \( O(1) \) as the complexity is effectively constant. The floor function also operates in constant time. Thus, the overall time complexity of the function is \( O(1) \).

Space Complexity

  • Function: long long int floorSqrt(long long int n):

    The function uses a constant amount of space for variables and function calls. There are no additional data structures that grow with the size of the input. Hence, the space complexity is \( O(1) \).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top