Square root of an integer

Given an integer x, find square root of it. If x is not a perfect square, then return floor(√x).

Examples :

Input: x = 4
Output: 2

Input: x = 11
Output: 3

There can be many ways to solve this problem. For example Babylonian Method is one way.

A Simple Solution to find floor of square root is to try all numbers starting from 1. For every tried number i, if i*i is smaller than x, then increment i. We stop when i*i becomes more than or equal to x. Below is the implementation of above idea.

C++



// A C++ program to find floor(sqrt(x)
#include<bits/stdc++.h>
using namespace std;
  
// Returns floor of square root of x
int floorSqrt(int x)
{
    // Base cases
    if (x == 0 || x == 1)
    return x;
  
    // Staring from 1, try all numbers until
    // i*i is greater than or equal to x.
    int i = 1, result = 1;
    while (result <= x)
    {
      i++;
      result = i * i;
    }
    return i - 1;
}
  
// Driver program
int main()
{
    int x = 11;
    cout << floorSqrt(x) << endl;
    return 0;
}

Java

// A Java program to find floor(sqrt(x))
  
class GFG {
      
    // Returns floor of square root of x
    static int floorSqrt(int x)
    {
        // Base cases
        if (x == 0 || x == 1)
            return x;
  
        // Staring from 1, try all numbers until
        // i*i is greater than or equal to x.
        int i = 1, result = 1;
          
        while (result <= x) {
            i++;
            result = i * i;
        }
        return i - 1;
    }
  
    // Driver program
    public static void main(String[] args)
    {
        int x = 11;
        System.out.print(floorSqrt(x));
    }
}
  
// This code is contributed by Smitha Dinesh Semwal.

Python3

# Python3 program to find floor(sqrt(x)
  
# Returns floor of square root of x
def floorSqrt(x):
  
    # Base cases
    if (x == 0 or x == 1):
        return x
  
    # Staring from 1, try all numbers until
    # i*i is greater than or equal to x.
    i = 1; result = 1
    while (result <= x):
      
        i += 1
        result = i * i
      
    return i - 1
  
# Driver Code
x = 11
print(floorSqrt(x))
  
# This code is contributed by Smitha Dinesh Semwal.

C#

// A C# program to 
// find floor(sqrt(x))
using System;
  
class GFG
{
    // Returns floor of
    // square root of x
    static int floorSqrt(int x)
    {
        // Base cases
        if (x == 0 || x == 1)
            return x;
  
        // Staring from 1, try all
        // numbers until i*i is 
        // greater than or equal to x.
        int i = 1, result = 1;
          
        while (result <= x) 
        {
            i++;
            result = i * i;
        }
        return i - 1;
    }
  
    // Driver Code
    static public void Main ()
    {
        int x = 11;
        Console.WriteLine(floorSqrt(x));
    }
}
  
// This code is contributed by ajit

PHP

<?php
// A PHP program to find floor(sqrt(x)
  
// Returns floor of square root of x
function floorSqrt($x)
{
    // Base cases
    if ($x == 0 || $x == 1)
    return $x;
  
    // Staring from 1, try all 
    // numbers until i*i is 
    // greater than or equal to x.
    $i = 1;
    $result = 1;
    while ($result <= $x)
    {
        $i++;
        $result = $i * $i;
    }
    return $i - 1;
}
  
// Driver Code
$x = 11;
echo floorSqrt($x), "\n";
  
// This code is contributed by ajit
?>


Output :

3

Time complexity of the above solution is O(√ n). Thanks Fattepur Mahesh for suggesting this solution.

A Better Solution to do Binary Search.

Let  's' be the answer.  We know that 0 <=  s <= x.

Consider any random number r. 

    If r*r = r

    If r*r > x, s < r. 

Algorithm:
1) Start with ‘start’ = 0, end = ‘x’,
2) Do following while ‘start’ is smaller than or equal to ‘end’.
      a) Compute ‘mid’ as (start + end)/2
      b) compare mid*mid with x.
      c) If x is equal to mid*mid, return mid.
      d) If x is greater, do binary search between mid+1 and end. In this case, we also update ans (Note that we need floor).
      e) If x is smaller, do binary search between start and mid

Below is the implementation of above idea.

C/C++

// A C++ program to find floor(sqrt(x)
#include<bits/stdc++.h>
using namespace std;
  
// Returns floor of square root of x         
int floorSqrt(int x) 
{    
    // Base cases
    if (x == 0 || x == 1) 
       return x;
  
    // Do Binary Search for floor(sqrt(x))
    int start = 1, end = x, ans;   
    while (start <= end) 
    {        
        int mid = (start + end) / 2;
  
        // If x is a perfect square
        if (mid*mid == x)
            return mid;
  
        // Since we need floor, we update answer when mid*mid is 
        // smaller than x, and move closer to sqrt(x)
        if (mid*mid < x) 
        {
            start = mid + 1;
            ans = mid;
        
        else // If mid*mid is greater than x
            end = mid-1;        
    }
    return ans;
}
   
// Driver program
int main() 
{     
    int x = 11;
    cout << floorSqrt(x) << endl;
    return 0;   
}

Java

// A Java program to find floor(sqrt(x)
public class Test
{
    public static int floorSqrt(int x)
    {
        // Base Cases
        if (x == 0 || x == 1)
            return x;
  
        // Do Binary Search for floor(sqrt(x))
        int start = 1, end = x, ans=0;
        while (start <= end)
        {
            int mid = (start + end) / 2;
  
            // If x is a perfect square
            if (mid*mid == x)
                return mid;
  
            // Since we need floor, we update answer when mid*mid is
            // smaller than x, and move closer to sqrt(x)
            if (mid*mid < x)
            {
                start = mid + 1;
                ans = mid;
            }
            else   // If mid*mid is greater than x
                end = mid-1;
        }
        return ans;
    }
  
    // Driver Method
    public static void main(String args[])
    {
        int x = 11;
        System.out.println(floorSqrt(x));
    }
}
// Contributed by InnerPeace

Python3

# Python 3 program to find floor(sqrt(x)
  
# Returns floor of square root of x         
def floorSqrt(x) :
  
    # Base cases
    if (x == 0 or x == 1) :
        return x
   
    # Do Binary Search for floor(sqrt(x))
    start = 1
    end = x   
    while (start <= end) :
        mid = (start + end) // 2
          
        # If x is a perfect square
        if (mid*mid == x) :
            return mid
              
        # Since we need floor, we update 
        # answer when mid*mid is smaller
        # than x, and move closer to sqrt(x)
        if (mid * mid < x) :
            start = mid + 1
            ans = mid
              
        else :
              
            # If mid*mid is greater than x
            end = mid-1
              
    return ans
  
# driver code    
x = 11
print(floorSqrt(x))
      
# This code is contributed by Nikita Tiwari.

C#

// A C# program to 
// find floor(sqrt(x)
using System;
  
class GFG
{
    public static int floorSqrt(int x)
    {
        // Base Cases
        if (x == 0 || x == 1)
            return x;
  
        // Do Binary Search 
        // for floor(sqrt(x))
        int start = 1, end = x, ans = 0;
        while (start <= end)
        {
            int mid = (start + end) / 2;
  
            // If x is a 
            // perfect square
            if (mid * mid == x)
                return mid;
  
            // Since we need floor, we 
            // update answer when mid * 
            // mid is smaller than x, 
            // and move closer to sqrt(x)
            if (mid * mid < x)
            {
                start = mid + 1;
                ans = mid;
            }
              
            // If mid*mid is 
            // greater than x
            else 
                end = mid-1;
        }
        return ans;
    }
  
    // Driver Code
    static public void Main ()
    {
        int x = 11;
        Console.WriteLine(floorSqrt(x));
    }
}
  
// This code is Contributed by m_kit

PHP

<?php
// A PHP program to find floor(sqrt(x)
  
// Returns floor of 
// square root of x         
function floorSqrt($x
    // Base cases
    if ($x == 0 || $x == 1) 
    return $x;
  
    // Do Binary Search 
    // for floor(sqrt(x))
    $start = 1; $end = $x; $ans
    while ($start <= $end
    
        $mid = ($start + $end) / 2;
  
        // If x is a perfect square
        if ($mid * $mid == $x)
            return $mid;
  
        // Since we need floor, we update 
        // answer when mid*mid is  smaller
        // than x, and move closer to sqrt(x)
        if ($mid * $mid < $x
        {
            $start = $mid + 1;
            $ans = $mid;
        
          
        // If mid*mid is 
        // greater than x
        else 
            $end = $mid-1;     
    }
    return $ans;
}
  
// Driver Code
$x = 11;
echo floorSqrt($x), "\n";
  
// This code is contributed by ajit
?>


Output :

3

Time Complexity: O(Log x)

Thanks to Gaurav Ahirwar for suggesting above method.

Note: The Binary Search can be further optimized to start with ‘start’ = 0 and ‘end’ = x/2. Floor of square root of x cannot be more than x/2 when x > 1.

Thanks to vinit for suggesting above optimization.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : jit_t, FarhanSheik, YashGupta12