The basic idea is that if x is an overestimate to the square root of a non-negative real number S then will be an underestimate and so the average of these two numbers may reasonably be expected to provide a better approximation (though the formal proof of that assertion depends on the inequality of arithmetic and geometric means that shows this average is always an overestimate of the square root, as noted in the article on square roots, thus assuring convergence).
If we are sure that n is a perfect square, then we can use following method. The method can go in infinite loop for non-perfect-square numbers. For example, for 3 the below while loop will never terminate.
Read full article from Babylonian method for square root | GeeksforGeeks
1 Start with an arbitrary positive start value x (the closer to the root, the better). 2 Initialize y = 1. 3. Do following until desired approximation is achieved. a) Get the next approximation for root using average of x and y b) Set y = n/x
float
squareRoot(
float
n)
{
/*We are using n itself as initial approximation
This can definitely be improved */
float
x = n;
float
y = 1;
float
e = 0.000001;
/* e decides the accuracy level*/
while
(x - y > e)
{
x = (x + y)/2;
y = n/x;
}
return
x;
}
unsigned
int
squareRoot(
int
n)
{
int
x = n;
int
y = 1;
while
(x > y)
{
x = (x + y)/2;
y = n/x;
}
return
x;