Square Root of an Integer in JavaScript
2 min readJun 7, 2022
Different approaches to solve the problem
Approach 1: Using the built-in methods
Approach 2: Try all natural numbers from 1
- If the number is 0 or 1, then return the number
- Create two variables, one will be the counter and the other will store the squares of the counter
- Loop till the square of the counter is less than or equal to the given number
- Increment the counter variable by one and update the value of the other variable
- Return the counter
Time Complexity: O(√n)
Space Complexity: O(1)
Approach 3: Binary Search
- This function will accept a number (x) as an argument
- Create two variables, low and high and initialize them to 0 and x
- Create a loop with the condition being
low < high
- Find the mid-value
floor((low + high) / 2)
- If the square of mid-value is equal to x, return mid
- If it's greater than x,
high = mid - 1
- Otherwise,
low = mid + 1
- If
x < high * high
returnhigh - 1
- Else return
high
Note: We are taking the value of high floor(high/2)
because the floor of the square root of x cannot be more than x/2 when x > 1.
Time Complexity: O(log n)
Space Complexity: O(1)