# Square root of an integer number

Page 2/5
1 | | 3 | 4 | 5

The following routine (by Ricardo Bittencourt) takes 8 iterations for any 16 bit number

;Square root of 16-bit value
;In: HL = value
;Out: D = result (rounded down)
;
Sqr16: ld de,#0040
ld a,l
ld l,h
ld h,d
or a
ld b,8
Sqr16_Loop:
sbc hl,de
jr nc,Sqr16_Skip
Sqr16_Skip:
ccf
rl d
djnz Sqr16_Loop
ret

hehehe
I'm sure that the one I posted was not the best way, but it was so simple that I could not resist
Ricardo's code seems an implementation of the Bombelli algorithm
Here a description (sorry, in Italian) and a C snippet implementing it:

Well, there is no "best" way, it all depends on the requirements. If you don't care about speed and need the smallest possible code, then your solution is the best (if you change jp to jr .).

(sorry, in Italian)Well, there's a small box on hte left hand side of that page titled altre lingue and in that box you'll find a link to the english version of the page :P

ARTRAG: of course the one I posted cannot compete with anything. It's just that I wanted to say that your algo sounds like a LOT more efficient than Newton Raphson! Also my ASM implementation was a direct port from the algorithm, without trying to optimize anything. Ah well, pure educational purposes

This way ARTRAG's routine is probably always faster:

```; in hl
; out a

ld  de,1
xor a
1:
sbc hl,de
ret c
inc e
inc e
inc a
jp  1b
```

But it won't work after the 127th iteration, 'cause after DE=255 you'll have DE=1. I'm afraid that INC DE is required instead of INC E.

It isn't always that much faster also. Ah well, I better go back to sleep now

Well, your approach of avoiding the repetition of XOR A in every iteration produces a sensible overall improvement. We, anonymous assemblers (A.A.), do live for optimization ;D. I'm really high on size optimization. What's your dope? ;D

Page 2/5
1 | | 3 | 4 | 5