# to the nth power

Herman Rubin cik at l.cc.purdue.edu
Fri Nov 9 00:36:28 AEST 1990


In article <1990Nov3.220554.19404 at zoo.toronto.edu>, henry at zoo.toronto.edu (Henry Spencer) writes:
> In article <3809 at idunno.Princeton.EDU> pfalstad at phoenix.Princeton.EDU (Paul John Falstad) writes:
> >Just out of curiosity, is there an efficient algorithm for finding
> >square root of an integer (or the integral part of the square root, if
> >the number is not a perfect square) using only integer arithmetic?
 
> It's not difficult using Newton's Method, i.e. successive approximations,
> if you have good integer division.  Like this:
 
> 	sqrtx = ( sqrtx + x/sqrtx ) / 2
 
> although you'll have to watch roundoff effects to avoid the possibility
> of an infinite loop when the square root isn't exact.  You also need an
> initial approximation, although just x/2 is a good start.

Assuming this is done in integer arithmetic, there is only one case of an
infinite loop.  Using real arithmetic (of course impossible on a computer),
the iteration is always too large.  Thus it should be rounded down.  Now
it is possible that this makes it so small that the next iteration is
larger.  If one starts with something too large, this can only happen
if x = n(n+2), and this can be detected by the iterate being larger than
the previous value, so that a stopping rule when the iterate does not
decrease, and taking the previous value, is always right, if the initial
value is too large.
-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (Internet, bitnet)   {purdue,pur-ee}!l.cc!hrubin(UUCP)



More information about the Comp.lang.c mailing list