Título: Square root of integers Publicado por: ARTRAG en 15 de Diciembre de 2008, 10:57:53 pm Código: The square root of an integer is equal to the number of times an increasing odd number can be subtracted from the original number and remain positive. For example, 25 - 1 1 -- 24 - 3 2 -- 21 - 5 3 -- 16 - 7 4 -- 9 - 9 5 = square root of 25 -- 0 Nice to keep in mind... Título: Re: Square root of integers Publicado por: pitpan en 15 de Diciembre de 2008, 11:12:50 pm Something like this?
Código: ;--------------------- SQUARE_ROOT: ;--------------------- ; Input: ; A=integer (0-255) ; Output: ; B=square root of A ; Modifies: ; AF,BC ;--------------------- ld bc,0001h @@LOOP: sub c ret m inc b inc c inc c jr @@LOOP ;--------------------- (not tested, of course) (not sure about RET M, does it mean to check C and Z?) Ok. Updated to shorten the program 1 byte. Now it's only 10 bytes! Título: Re: Square root of integers Publicado por: ARTRAG en 15 de Diciembre de 2008, 11:53:46 pm Or something like this:
Código: ; in hl ; out a ld de,1 ld a,d 1: and a sbc hl,de ret m inc de inc de inc a jp 1b Untested too!! Título: Re: Square root of integers Publicado por: pitpan en 16 de Diciembre de 2008, 07:02:36 am Cool 16-bit version, AR!
Due to the elegance of this solution, it is possible even to produce such a routine to calculate the square root of a binary packed decimal number (BCD). Amazing that it could be so simple! Título: Re: Square root of integers Publicado por: ARTRAG en 16 de Diciembre de 2008, 10:50:57 am The following routine (by Ricardo Bittencourt) takes 8 iterations for any 16 bit number
Código: ;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 add hl,de Sqr16_Skip: ccf rl d add a,a adc hl,hl add a,a adc hl,hl djnz Sqr16_Loop ret |