Square root
PROBLEM :
Given an integer x , Your task is to find the square root of it. If x is not a perfect square, then return floor(vx)
Input:
You have to complete the method which takes 1 argument: the integer N. You should not read any input from stdin/console. There are multiple test cases. For each test cases, this method will be called individually.
Output:
Your function should return square root of given integer.
Constraints:
1 = T = 1000
1 = N = 1000000
Example:
Input
2
5
4
Output
2
2
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(n)
--------------------------------------------------------------------------------
/*You are required to complete
this function*/
long long int floorSqrt(long long int x)
{
if(x==1||x==0)
return x ;
int i,ans ;
for(i=1;i<=(x/2);i++)
{
if(i*i==x)
return i ;
else if(i*i<x)
ans=i ;
else
break ;
}
return ans ;
}
-------------------------------------------------------------------------------
BETTER SOLUTION : O(logn)
--------------------------------------------------------------------------------
/*You are required to complete
this function*/
long long int floorSqrt(long long int x)
{
if(x==1||x==0)
return x ;
int start,end,mid,ans ;
start=1;
end=x ;
while(start<=end)
{
mid=(start+end)/2 ;
if(mid*mid<x)
{
start=mid+1 ;
ans=mid ;
}
else if(mid*mid>x)
end=mid-1 ;
else
return mid ;
}
return ans ;
}
---------------------------------------------------------------------------------
Given an integer x , Your task is to find the square root of it. If x is not a perfect square, then return floor(vx)
Input:
You have to complete the method which takes 1 argument: the integer N. You should not read any input from stdin/console. There are multiple test cases. For each test cases, this method will be called individually.
Output:
Your function should return square root of given integer.
Constraints:
1 = T = 1000
1 = N = 1000000
Example:
Input
2
5
4
Output
2
2
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(n)
--------------------------------------------------------------------------------
/*You are required to complete
this function*/
long long int floorSqrt(long long int x)
{
if(x==1||x==0)
return x ;
int i,ans ;
for(i=1;i<=(x/2);i++)
{
if(i*i==x)
return i ;
else if(i*i<x)
ans=i ;
else
break ;
}
return ans ;
}
-------------------------------------------------------------------------------
BETTER SOLUTION : O(logn)
--------------------------------------------------------------------------------
/*You are required to complete
this function*/
long long int floorSqrt(long long int x)
{
if(x==1||x==0)
return x ;
int start,end,mid,ans ;
start=1;
end=x ;
while(start<=end)
{
mid=(start+end)/2 ;
if(mid*mid<x)
{
start=mid+1 ;
ans=mid ;
}
else if(mid*mid>x)
end=mid-1 ;
else
return mid ;
}
return ans ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment