Amazon Interview Question: Calculate the square root of ... | Glassdoor

Interview Question

Software Development Engineer Intern Interview Seattle, WA

Calculate the square root of a number.

Answer

Interview Answer

3 Answers

4

public double squareRoot(double x)
    {
        double epsilon = 0.000001;
        double base = 0;
        double increment = 1;
        while (increment > epsilon)
        {
            double diff = base*base - x;
            if (diff 0)
            {
                base -= increment;
                increment /= 10;
            }
            else
            {
                break;
            }
        }
        return base;
    }

Ozan Eren Bilgen on Oct 18, 2012
4

private static double sqrt(double n)
    {
        double lower = 0;
        double upper = n;
        for (int i = 0; i < 1000; i++)
        {
            double mid = (lower + upper) / 2;
            if (mid * mid < n)
                lower = mid;
            else upper = mid;
        }
        return (lower + upper) / 2;
    }

Gingko on Nov 4, 2012
0

#include
#include
using namespace std;
#include
 int main()
{
float n;
cout>n;
if(n0.00001)
{

if(mid*midn)
high=mid;
mid=(low+high)/2;
}
return mid;
}

Akhil jain on Feb 16, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.