lsqrt.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* lsqrt.c
  2. *
  3. * Integer square root
  4. *
  5. *
  6. *
  7. * SYNOPSIS:
  8. *
  9. * long x, y;
  10. * long lsqrt();
  11. *
  12. * y = lsqrt( x );
  13. *
  14. *
  15. *
  16. * DESCRIPTION:
  17. *
  18. * Returns a long integer square root of the long integer
  19. * argument. The computation is by binary long division.
  20. *
  21. * The largest possible result is lsqrt(2,147,483,647)
  22. * = 46341.
  23. *
  24. * If x < 0, the square root of |x| is returned, and an
  25. * error message is printed.
  26. *
  27. *
  28. * ACCURACY:
  29. *
  30. * An extra, roundoff, bit is computed; hence the result
  31. * is the nearest integer to the actual square root.
  32. * NOTE: only DEC arithmetic is currently supported.
  33. *
  34. */
  35. /*
  36. Cephes Math Library Release 2.0: April, 1987
  37. Copyright 1984, 1987 by Stephen L. Moshier
  38. Direct inquiries to 30 Frost Street, Cambridge, MA 02140
  39. */
  40. #include <math.h>
  41. long lsqrt(x)
  42. long x;
  43. {
  44. long num, sq;
  45. long temp;
  46. int i, j, k, n;
  47. if( x < 0 )
  48. {
  49. mtherr( "lsqrt", DOMAIN );
  50. x = -x;
  51. }
  52. num = 0;
  53. sq = 0;
  54. k = 24;
  55. n = 4;
  56. for( j=0; j<4; j++ )
  57. {
  58. num |= (x >> k) & 0xff; /* bring in next byte of arg */
  59. if( j == 3 ) /* do roundoff bit at end */
  60. n = 5;
  61. for( i=0; i<n; i++ )
  62. {
  63. num <<= 2; /* next 2 bits of arg */
  64. sq <<= 1; /* shift up answer */
  65. temp = (sq << 1) + 256; /* trial divisor */
  66. temp = num - temp;
  67. if( temp >= 0 )
  68. {
  69. num = temp; /* it went in */
  70. sq += 256; /* answer bit = 1 */
  71. }
  72. }
  73. k -= 8; /* shift count to get next byte of arg */
  74. }
  75. sq += 256; /* add roundoff bit */
  76. sq >>= 9; /* truncate */
  77. return( sq );
  78. }