Ebay Interview Question
Software Engineer / DevelopersTeam: cloud
Country: United States
Interview Type: Phone Interview
the sum of a sequence of odd numbers gives you the sequence for the perfect squares
1=1
1+3=4
1+3+5=9
1+3+5+7=16
Java: [based on binary search method]
double FindSquareRoot(double n)
{
double sr;
final double ERROR = 0.00001;
return FindRootByBinarySearch(n, 0, n/2, ERROR);
}
double FindRootByBinarySearch(double n, double low, double high, double ERROR)
{
if ((high-low) < ERROR)
return low;
double mid = (high+low)/2;
if ((mid*mid)>n)
return FindRootByBinarySearch(n, low, mid, ERROR);
else
return FindRootByBinarySearch(n, mid, high, ERROR);
}
Can be done in O(1) me thinks (for a range of inputs numbers for our application).
Use Taylor's polynomial theorem.
Find polynomial expansion of sqrt(1+x) about x=0.
For the required range of inputs, design the expansion to have degree K such that the error is within required precision for the range of inputs.
Now you have a polynomial p(x) of degree K to use for your application.
{{
sqrt(num)
{
// evaluate the special polynomial at x= num -1
// above can be done with O(K) operations. K is fixed.
return whatever you got ;
}
}}}
A simple binary search method.
The idea is f(x) = x^2 is monotonically increasing function.
So to find sqrt of Y. We need to find an x such that x * x = Y.
We start with initial guesses 0 and Y and keep bisecting the range Y in which we know the sqrt cannot lie.
- Anonymous October 21, 2011