sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

_________________________________________________________________________________________________________

Solution: Newton’s Method of Approximation

http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/

int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x==0)
return 0;

double result = (double)x;
double temp = 1.0;

while(result-temp>0.001||result-temp<-0.001)
{
temp=result;

result = temp/2 + x/(2*temp);//would convergent to real solution.
}

return result;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s