Square Root of an Integer in C++

By | August 15, 2020

Given an integer n, find value of its square root.

Examples :

Input: n = 16
Output: 4 

Input: n = 8
Output: 2 

Note – floor value of 2.8 is 2.

There can be many ways to solve this problem.

Method-1: Simple Approach, in O(√ n) time complexity

#include<bits/stdc++.h> 
using namespace std; 
  
// floor of square root of n 
int floorSqrt(int n) 
{ 
    // Base cases 
    if (n == 0 || n == 1) 
    return n; 
   
    int i = 1, result = 1; 
    while (result <= n) 
    { 
      i++; 
      result = i * i; 
    } 
    return i - 1; 
} 
  
// Driver program 
int main() 
{ 
    int n = 16; 
    cout << floorSqrt(n) << endl; 
    return 0; 
} 

Output :

2

Note –
If n is not a perfect square, then return floor(√n).


Method-2: Better Approach, in O(log n) time complexity

#include<bits/stdc++.h> 
using namespace std; 
int floorSqrt(int n) {
    if (n==0) return 0;
    int left = 1;
    int right = n/2 + 1;
    int res;

    while (left <= right) {
        int mid = left + ((right-left)/2);
        if (mid<=n/mid){
            left = mid+1;
            res=mid;
        }
        else {
            right=mid-1;
        }
    }

    return res;
}
  
// Driver program 
int main() 
{ 
    int n = 8; 
    cout << floorSqrt(n) << endl; 
    return 0; 
} 

Output :

2

Note –
If n is not a perfect square, then return floor(√n).


Method-3: Using Babylonian method

#include <iostream> 
using namespace std; 
class cpp { 
   
public: 
    float squareRoot(float n) 
    { 
    
        float x = n; 
        float y = 1; 
        float e = 0.000001; 
        while (x - y > e) { 
            x = (x + y) / 2; 
            y = n / x; 
        } 
        return x; 
    } 
}; 
  
// Driver program 
int main() 
{ 
    cpp p; 
    int n = 16; 
    cout << "Square root of " << n << " is " << p.squareRoot(n);  
} 

Output :

Square root of 9 is 3 


Method-4: Using sqrt() function defined in math.h header file

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	double n = 8, result;
	result = sqrt(x);
	cout << "Square root of " << n << " is " << result << endl;

	return 0;
}

Output :

Square root of 8 is 2.82843

Note –
Square root in C++ can be calculated using sqrt() function defined in math.h header file. This function takes a number as an argument and returns the square root of that number.



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.