Open In App

Square root of an integer

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer X, find its 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.

Recommended Practice

Naive 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.

Follow the steps below to implement the above idea

  1. Create a variable (counter) i and take care of some base cases, (i.e when the given number is 0 or 1).
  2. Run a loop until i*i <= n, where n is the given number. Increment i by 1.
  3. The floor of the square root of the number is i – 1

Below is the implementation of the above approach:

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;
 
    // 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
int main()
{
    int x = 11;
    cout << floorSqrt(x) << endl;
    return 0;
}


C




#include <stdio.h>
 
// Returns floor of square root of x
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
int main()
{
    int x = 11;
    printf("%d\n", floorSqrt(x));
    return 0;
}
// code is contributed by lalith kumar.g


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;
 
        // 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




# 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
 
    # 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 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;
 
        // 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




<?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;
 
    // 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
?>


Javascript




<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;
 
    // 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 Code
let x = 11;
document.write(floorSqrt(x));
 
// This code is contributed by mohan
 
</script>


Output

3

Complexity Analysis: 

  • Time Complexity: O(√X). Only one traversal of the solution is needed, so the time complexity is O(√X).
  • Auxiliary Space: O(1).

Thanks, Fattepur Mahesh for suggesting this solution. 

Square root an integer using Binary search:

The idea is to find the largest integer i whose square is less than or equal to the given number. The values of i * i is monotonically increasing, so the problem can be solved using binary search.

Below is the implementation of the above idea: 

  1. Base cases for the given problem are when the given number is 0 or 1, then return X;
  2. Create some variables, for storing the lower bound say l = 0, and for upper bound r = X / 2 (i.e, The floor of the square root of x cannot be more than x/2 when x > 1).
  3. Run a loop until l <= r, the search space vanishes
  4. Check if the square of mid (mid = (l + r)/2 ) is less than or equal to X, If yes then search for a larger value in the second half of the search space, i.e l = mid + 1, update ans = mid
  5. Else if the square of mid is more than X then search for a smaller value in the first half of the search space, i.e r = mid – 1
  6. Finally, Return the ans

Below is the implementation of the above approach:

C++




#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 program
int main()
{
    int x = 11;
    cout << floorSqrt(x) << endl;
    return 0;
}


C




#include <math.h>
#include <stdio.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 / 2, 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


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))
        long start = 1, end = x / 2, 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


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//2
    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 / 2, 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/2; $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
?>


Javascript




<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/2;
    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 Code
let x = 11;
document.write(floorSqrt(x) +  "<br>");
 
// This code is contributed by _saurabh_jaiswal
</script>


Output

3

Complexity Analysis: 

  • Time Complexity: O(log(X)). 
  • Auxiliary Space: O(1).

Thanks to Gaurav Ahirwar for suggesting the above method.

Square root an integer using built-in functions:

Below is the implementation for finding the square root using the built-in function. 

C++




#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


C




#include <math.h>
#include <stdio.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


Java




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


Python3




def countSquares(x):
    sqrt = x**0.5
    result = int(sqrt)
    return result
 
 
x = 9
print(countSquares(x))


C#




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


Javascript




<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

Time Complexity: O(log(X))
Auxiliary Space: O(1)

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

Another Approach to Solve This Problem Using Exponential Function:

The basic idea behind the method is to calculate the exponential of the logarithm of the integer divided by two. 

Below are steps to implement the above approach:

  • Take the integer value as input and save it in a variable.
  • Use the exponential function exp() and the logarithmic function log() from the <cmath> library to calculate the square root of the integer. exp(log(x) / 2) will give the square root of x.
  • Use the floor() function to get the integer part of the result.
  • Check whether the square of the floor result is equal to the input x.
  • If the square of the floor result is equal to the input x, then return the floor result as it is the square root of x.
  • If the square of the floor result is not equal to the input x, then return the floor result as the floor of the square root

Below is the implementation of the above approach:

C++




// C++ code to implement the above approach
#include <iostream>
// header file for math functions
#include <cmath>
 
using namespace std;
int findSquareRoot(int x)
{
    // using exponential and logarithmic function to
    // calculate square root of x
    double result = exp(log(x) / 2);
    // floor function to get integer part of the result
    int floorResult = floor(result);
 
    // If the integer square of the floor result is equal to
    // the input x,
    // then x is a perfect square, and floor result is the
    // square root.
    if (floorResult * floorResult == x) {
        return floorResult;
    }
    else { // If not, then x is not a perfect square, and
           // floor result is the floor of the square root.
        return floorResult;
    }
}
 
// Driver code
int main()
{
    int x = 11;
    int squareRoot = findSquareRoot(
        x); // calling the findSquareRoot function to
            // calculate the square root
 
    cout << squareRoot << endl; // printing the result
 
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot


Java




// java code to implement the above approach
import java.lang.Math;
 
public class Main {
    public static int findSquareRoot(int x)
    {
        // using exponential and logarithmic function to
        // calculate square root of x
        double result = Math.exp(Math.log(x) / 2);
        // floor function to get integer part of the result
        int floorResult = (int)Math.floor(result);
 
        // If the integer square of the floor result is
        // equal to the input x, then x is a perfect square,
        // and floor result is the square root.
        if (floorResult * floorResult == x) {
            return floorResult;
        }
        else { // If not, then x is not a perfect square,
               // and floor result is the floor of the
               // square root.
            return floorResult;
        }
    }
    // Driver code
    public static void main(String[] args)
    {
        int x = 11;
        int squareRoot = findSquareRoot(
            x); // calling the findSquareRoot function to
                // calculate the square root
 
        System.out.println(
            squareRoot); // printing the result
    }
}
// This code is contributed by Veerendra_Singh_Rajpoot


Python3




# Python code to implement the above approach
import math
 
def findSquareRoot(x):
   
    # using exponential and logarithmic function to
    # calculate square root of x
    result = math.exp(math.log(x) / 2)
     
    # floor function to get integer part of the result
    floorResult = math.floor(result)
 
    # If the integer square of the floor result is equal to
    # the input x,
    # then x is a perfect square, and floor result is the
    # square root.
    if floorResult * floorResult == x:
        return floorResult
    else:
        # If not, then x is not a perfect square, and
        # floor result is the floor of the square root.
        return floorResult
 
 
# Driver code
x = 11
 
# calling the findSquareRoot function to calculate the square root
squareRoot = findSquareRoot(x)
print(squareRoot)  # printing the result


C#




using System;
 
public class Program
{
    public static int FindSquareRoot(int x)
    {
        // using exponential and logarithmic function to
        // calculate square root of x
        double result = Math.Exp(Math.Log(x) / 2);
 
        // floor function to get integer part of the result
        int floorResult = (int)Math.Floor(result);
 
        // If the integer square of the floor result is equal to
        // the input x,
        // then x is a perfect square, and floor result is the
        // square root.
        if (floorResult * floorResult == x)
        {
            return floorResult;
        }
        else
        {
            // If not, then x is not a perfect square, and
            // floor result is the floor of the square root.
            return floorResult;
        }
    }
 
    public static void Main()
    {
        int x = 11;
        int squareRoot = FindSquareRoot(x); // calling the FindSquareRoot function to calculate the square root
        Console.WriteLine(squareRoot); // printing the result
    }
}


Javascript




function findSquareRoot(x) {
    // using exponential and logarithmic function to
    // calculate square root of x
    let result = Math.exp(Math.log(x) / 2);
    // floor function to get integer part of the result
    let floorResult = Math.floor(result);
 
    // If the integer square of the floor result is equal to
    // the input x,
    // then x is a perfect square, and floor result is the
    // square root.
    if (floorResult * floorResult == x) {
        return floorResult;
    } else {
        // If not, then x is not a perfect square, and
        // floor result is the floor of the square root.
        return floorResult;
    }
}
 
// Driver code
let x = 11;
let squareRoot = findSquareRoot(x);// calling the findSquareRoot function to
            // calculate the square root
 
console.log(squareRoot); // printing the result


Output

3

Time Complexity: O(1), The time complexity of the given approach is O(1) since it uses only one mathematical formula exp(log(x) / 2) which is constant time, and a few arithmetic operations, comparisons, and function calls that take constant time as well. Therefore, the time complexity of this algorithm is constant or O(1).
Auxiliary Space: O(1), The space complexity of the given approach is O(1) as it only uses a constant amount of extra space. It declares two integer variables, result and floorResult, which each take constant space, and there is no dynamic memory allocation or recursive calls. Therefore, the space complexity of this algorithm is constant or O(1).



Previous Article
Next Article

Similar Reads

Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Largest integer upto N having greatest prime factor greater than its square root
Given a positive integer N, the task is to find the largest number in the range [1, N] such that the square root of the number is less than its greatest prime factor. Input: N = 15Output: 15Explanation: The prime factors of 15 are {3, 5}. The square root of 15 is 3.87 (i.e, 3.87 &lt; 5). Therefore 15 is the largest valid integer in the given range.
7 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 &lt;= N &lt;= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Digital Root (repeated digital sum) of the given large integer
The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.Given a number, t
5 min read
Babylonian method for square root
Algorithm: This method can be derived from (but predates) Newton–Raphson method. 1 Start with an arbitrary positive start value x (the closer to the root, the better). 2 Initialize y = 1. 3. Do following until desired approximation is achieved. a) Get the next approximation for root using average of x and y b) Set y = n/x Implementation: C/C++ Code
9 min read
Find square root of number upto given precision using binary search
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: Input : number = 50, precision = 3 Output : 7.071 Input : number = 10, precision = 4 Output : 3.1622 We have discussed how to compute the integral value of square root in Square Root usin
9 min read
Fast inverse square root
Fast inverse square root is an algorithm that estimates [Tex]{\dfrac{1}{\sqrt{x}}} [/Tex], the reciprocal (or multiplicative inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point format. Computing reciprocal square roots is necessary in many applications, such as vector normalization in video games and is mostly
6 min read
Program to calculate Root Mean Square
Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 3.31662 Input: arr[] = {10, 4, 6, 8} Output: 7.34847 Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, RMS method first calculates the square of each number and then
4 min read