( sqrt DAY 06.04.2001 )

\ precise integer square root 
\ with rounding
\ Newton's method

: sqrt ( n1 -- n2 )
   dup 0< abort" negative arg"
   dup 2 < if exit then
   dup >r dup 2/
   begin
     2dup / + dup 1 rshift
     swap 1 and +
     dup r@ < if rdrop dup >r 
              else 
                 drop r@ dup *
                 - negate r@ =
                 r> swap if 1- then
                 exit
              then
   again
;

\ adapted from 4th

: log2  ( n -- log2 )
        -1 swap
        begin
          dup
         while
          swap 1+ swap 
          1 rshift
        repeat drop
;

: exp  ( n1 n2 - n1**n2)
        1 rot rot
        begin
          dup
        while
          2 /mod >r
          if
            swap over * swap
          then
          dup * r>
        repeat
        drop drop
;
