Sorry, but you had better to use an iterative function, as you see your recursion is final recursion, that can be collapsed to a while
loop. Your algorithm is:
#include <stdio.h>
unsigned isqrt(unsigned x)
{
unsigned quot = 1, mean = x; /* isqrt must be between these two */
/* we begin with extreme numbers and for each pair of (quot,mean),
* the first, below the square root, and the other above, we get
* mean value of the two (lesser than previous) and the
* quotient (above the prev. value, but still less than the
* square root, so closer to it) to get a better approach */
while (quot < mean) {
mean = (mean + quot) >> 1;
quot = x / mean;
}
/* quot is always <= mean so finally it should be the same,
* we can return quot or mean, indistinctly. */
return mean;
}
int main() /* main test function, eliminate to use the above. */
{
unsigned n;
while (scanf("%u", &n) == 1) {
printf("isqrt(%u) ==> %u\n", n, isqrt(n));
}
}
EDIT
This algorithm is based on the fact that the geometric mean is always closer to 1 than the arithmetic mean. So we take two approximations (the source number and 1, as their geometric mean is the square root) then we calculate their arithmetic mean (so the value obtained is between both, and so, closer to the geometric mean) then we divide the original number by the arithmetic mean so both aproximations multiply to the original data (and their geometric mean is, again, the square root). As, in each loop the arithmetic mean is closer to the geometric mean, so must be the quotient (and so the quotient to the geometric mean), leading to two numbers that are closer to the square root. We continue the algorithm until both numbers are equal (a / sqrt(a) = sqrt(a)
, and (sqrt(a) + sqrt(a))/2 = sqrt(a)
) or, due to rounding errors, they cross over. ---this happens with integers---