Square root of an integer

23 Jun, 2022
Given an integer x, find it’s square root. If x is not a perfect square, then return floor(√x).
Examples : 
Input: x = 4
Output: 2
Explanation:  The square root of 4 is 2.

Input: x = 11
Output: 3
Explanation:  The square root of 11 lies in between
3 and 4 so floor of the square root is 3.
There can be many ways to solve this problem. For example, the Babylonian Method is one way.Simple Approach: To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number.
Algorithm: Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1
Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1
Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.
Run a loop until i*i <= n , where n is the given number. Increment i by 1.
The floor of the square root of the number is i – 1
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// A C++ program to find floor(sqrt(x)#include<bits/stdc++.h>using namespace std; // Returns floor of square root of xint floorSqrt(int x){    // Base cases    if (x == 0 || x == 1)    return x;     // Starting 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 programint main(){    int x = 11;    cout << floorSqrt(x) << endl;    return 0;}
#include <stdio.h> // Returns floor of square root of xint floorSqrt(int x){    // Base cases    if (x == 0 || x == 1)    return x;     // Starting 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 programint main(){    int x = 11;    printf("%d\n",floorSqrt(x));  return 0;}//code is contributed by lalith kumar.g
// 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;         // Starting 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 program to find floor(sqrt(x) # Returns floor of square root of xdef floorSqrt(x):     # Base cases    if (x == 0 or x == 1):        return x     # Starting 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 Codex = 11print(floorSqrt(x)) # This code is contributed by Smitha Dinesh Semwal.
// 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;         // Starting 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// A PHP program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt($x){    // Base cases    if ($x == 0 || $x == 1)    return $x;     // Starting 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?>
<script> // A Javascript program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt(x){         // Base cases    if (x == 0 || x == 1)        return x;     // Starting from 1, try all    // numbers until i*i is    // greater than or equal to x.    let i = 1;    let result = 1;         while (result <= x)    {        i++;        result = i * i;    }    return i - 1;} // Driver Codelet x = 11;document.write(floorSqrt(x)); // This code is contributed by mohan </script>
Output :
3
Complexity Analysis: Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n).Space Complexity: O(1). Constant extra space is needed.
Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n).
Space Complexity: O(1). Constant extra space is needed.
Thanks Fattepur Mahesh for suggesting this solution. Better Approach: The idea is to find the largest integer i whose square is less than or equal to the given number. The idea is to use Binary Search to solve the problem. The values of i * i is monotonically increasing, so the problem can be solved using binary search. 
Algorithm: Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)
Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)
Take care of some base cases, i.e when the given number is 0 or 1.
Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.
Run a loop until l <= r , the search space vanishes
Check if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = mid
Else if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1
Print the value of answer ( ans)
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream> using namespace std;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/2, ans;    while (start <= end) {        int mid = (start + end) / 2;         // If x is a perfect square        int sqr = mid * mid;        if (sqr == 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;                   }            Here basically if we multiply mid with itself so           there will be integer overflow which will throw           tle for larger input so to overcome this           situation we can use long or we can just divide            the number by mid which is same as checking           mid*mid < x            */        if (sqr <= x) {            start = mid + 1;            ans = mid;        }        else // If mid*mid is greater than x            end = mid - 1;    }    return ans;} // Driver programint main(){    int x = 20221;    cout << floorSqrt(x) << endl;    return 0;}
#include <stdio.h>#include <math.h>  int floorSqrt(int x)    {        // Base Cases        if (x == 0 || x == 1)            return x;          // Do Binary Search for floor(sqrt(x))        long 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 (int)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 (int)ans;    }     // Driver Method    int main()    {        int x = 11;        printf("%d\n",floorSqrt(x));    } //Contributed by lalith kumar.g
// 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))        long start = 1, end = x, ans=0;        while (start <= end)        {            long mid = (start + end) / 2;             // If x is a perfect square            if (mid*mid == x)                return (int)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 (int)ans;    }     // Driver Method    public static void main(String args[])    {        int x = 11;        System.out.println(floorSqrt(x));    }}// Contributed by InnerPeace
# 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 = 11print(floorSqrt(x))     # This code is contributed by Nikita Tiwari.
// 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// 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?>
<script>    // A Javascript 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))    let start = 1;    let end = x;    let ans;    while (start <= end)    {        let 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 Codelet x = 11;document.write(floorSqrt(x) +  "<br>"); // This code is contributed by _saurabh_jaiswal</script>
Output :
142
Complexity Analysis: Time complexity: O(log n). The time complexity of the binary search is O(log n).Space Complexity: O(1). Constant extra space is needed.
Time complexity: O(log n). The time complexity of the binary search is O(log n).
Space Complexity: O(1). Constant extra space is needed.
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. The floor of the square root of x cannot be more than x/2 when x > 1.Thanks to visit for suggesting the above optimization.
Better Approach: The logic is simple as we can observe that for a perfect square number it’s square root represent the total no of the perfect square from 1 to x.
for ex:- sqrt(1)=1, sqrt(4)=2, sqrt(9)=3 ........ so on.
Algorithm:
                            1. find the square root of x and store in a variable sqrt.
                            2. Use the floor value of sqrt and store in variable result, because for non-perfect square number. it’s floor value gives the result.
                            3. return the result.
Implementation:
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int countSquares(int x){    int sqr = sqrt(x);    int result = (int)(sqr);    return result;}int main(){     int x = 9;    cout << (countSquares(x));     return 0;} // This code is contributed by Rajput-Ji
#include <stdio.h>#include <math.h>     static int countSquares(int x) {        int sqr = (int) sqrt(x);        int result = (int) (sqr);        return result;    } int main()    {        int x = 9;        printf("%d\n",countSquares(x));    }// This code is contributed by lalith kumar.g
import java.util.*; class GFG {    static int countSquares(int x) {        int sqr = (int) Math.sqrt(x);        int result = (int) (sqr);        return result;    }     public static void main(String[] args)    {        int x = 9;        System.out.print(countSquares(x));    }} // This code is contributed by Rajput-Ji
def countSquares(x):  sqrt = x**0.5  result = int(sqrt)  return resultx = 9print(countSquares(x))
using System;public class GFG {  static int countSquares(int x) {    int sqr = (int) Math.Sqrt(x);    int result = (int) (sqr);    return result;  }   public static void Main(String[] args) {    int x = 9;    Console.Write(countSquares(x));  }} // This code is contributed by Rajput-Ji
<script>    function countSquares(x) {        var sqr = parseInt( Math.sqrt(x));        var result = parseInt(sqr);        return result;    }         var x = 9;        document.write(countSquares(x)); // This code is contributed by Rajput-Ji</script>
Output:
3
Method:  Finding square root of an integer by using sqrt() function of math module.
Python3
# Python3 program to find (sqrt(x))from math import*n=4# using the sqrt functon of math# module finding the square root integerprint(round(sqrt(n))) # This code is contributed by gangarajula laxmi
2
Complexity AnalysisTime complexity:- O(log n)Auxiliary Space :-  O(1) 
Time complexity:- O(log n)
Auxiliary Space :-  O(1) 
jit_t
FarhanSheik
yhgupta
andrew1234
pulamolusaimohan
swamipatil158
_saurabh_jaiswal
amit aggrawal
surajrawat307
arorakashish0911
saurabh1990aror
ibrezm1
aakashpanda2000
Rajput-Ji
movshov
nitish705702
lalithkumarg20
dsoumi125
laxmigangarajula03
Accolite
Amazon
Binary Search
Microsoft
Ola Cabs
Snapdeal
Divide and Conquer
Mathematical
Accolite
Amazon
Microsoft
Snapdeal
Ola Cabs
Mathematical
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find a peak element
Median of two sorted arrays of same size
Allocate minimum number of pages
Quick Sort vs Merge Sort
Closest Pair of Points using Divide and Conquer algorithm
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays