Amazon.com

  www.amazon.com
  www.amazon.com

Interview Question

Software Development Engineer Intern Interview Seattle, WA

Calculate the square root of a number.

Answer

Interview Answer

3 Answers

3

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;
            }
            else 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<iostream>
#include<math.h>
using namespace std;
#include <stdlib.h>
 int main()
{
float n;
cout<<"Enter No:";
cin>>n;
if(n<0)
     {
    cout<<("negative don't have square roots");
    exit(0);
     }
float y=sqrt(n);
cout<<"sqrt is "<<y;
return(0);
}

float sqrt(float n)
{
float low=0,high=n;
float mid=(low+high)/2;
while(fabs(mid*mid-n)>0.00001)
{

if(mid*mid<n)
low=mid;
else if(mid*mid>n)
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.