Square Root of an Integer in JavaScript

Nilesh Saini
2 min readJun 7, 2022

--

Different approaches to solve the problem

Photo by Cookie the Pom on Unsplash

Approach 1: Using the built-in methods

Approach 2: Try all natural numbers from 1

  1. If the number is 0 or 1, then return the number
  2. Create two variables, one will be the counter and the other will store the squares of the counter
  3. Loop till the square of the counter is less than or equal to the given number
  4. Increment the counter variable by one and update the value of the other variable
  5. Return the counter

Time Complexity: O(√n)

Space Complexity: O(1)

Approach 3: Binary Search

  1. This function will accept a number (x) as an argument
  2. Create two variables, low and high and initialize them to 0 and x
  3. Create a loop with the condition being low < high
  4. Find the mid-value floor((low + high) / 2)
  5. If the square of mid-value is equal to x, return mid
  6. If it's greater than x, high = mid - 1
  7. Otherwise, low = mid + 1
  8. If x < high * high return high - 1
  9. 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)

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

No responses yet