Integer square root routine needed.

Roger Critchlow rec at elf115.uu.net
Thu Aug 3 04:33:12 AEST 1989


/*
** ALGORITHM 650:
** Efficient Square Root Implementation on the 68000
** Kenneth C. Johnson
** ACM Transactions on Mathematical Software,
** Vol 13, No. 2, June 1987, Pages 138-151.
**
** The result is rounded to the nearest integer
** unless TRUNCATE is #defined.
*/

typedef unsigned long uint;	/* 32 bit int for obsolete compiler :-) */

#define two_to_the(x)	((uint)1 << (x))

uint isqrt(x) uint x;
{
  register uint u, v, q, w;

  u = x;
  q = two_to_the(16) * (two_to_the(16)-1);

  if (u > q)
    return two_to_the(16);

  for (w = two_to_the(31); w > 0; w >>= 2) {
    v = (q - w) >> 1;
    if (u > v) {
      u -= v;
      q = v + w;
    } else
      q = v;
  }

  q >>= 1;

#if TRUNCATE
  return (u < q) ? q-1 : q;
#else
  return q;
#endif
}



More information about the Comp.lang.c mailing list