Monday, November 29, 2021
HomeTop Coding QuestionC++ program to find the Square root of a number in C++.

C++ program to find the Square root of a number in C++.

find the square root of a number

Given a number we have to find the square root of a number and print the resultant value .

So what is square root of number?

Square root of a number is calculated by mathematically

squareroot(num)=n*n

to solve this problem we have inbuilt library in c++ sqrt() which will make easier to calculate during any test.

Example:

input:36
output:6

input:25
output:5

Approach 1:Using sqrt function

Code-

#include<bits/stdc++.h>
using namespace std;
int main() {
   int num;
cout<<"Enter a number "<<endl;
   cin>>num;
   double root=sqrt(num);//this is stl library function.
   cout<<root<<endl;
    
}

Approach 2:Without sqrt function

Logic:

this method is same like binary search,  we will check square root of number between low and high value.
#include<bits/stdc++.h> 
using namespace std; 
int main() 
{	 
    cout<<"Enter a number"<<endl;
int num;
cin>>num;
int square;
if(num==0||num==1)
{
    square=num;
}
else
{
    
    //lets apply binary search concept here.
    int mid=0;
    int low=1;
    int high=num;
    	while (low <= high) 
	{		 
		int mid = (low + high) / 2; 
		if (mid*mid == num) 
		{
			return mid; 
        }
		if (mid*mid < num) 
		{ 
			low = mid + 1; 
			square = mid; 
		} 
		else 
		{
			high = mid-1;	
		}
	} 
    
}
cout<<square<<endl;
return 0;
} 

Output:

enter a number:16
4

Time complexity:0(logN)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments