ld b,a
ld a,c
ld c,b
- jr c,2$
- call div0
- jr c,3$
-1$: ld d,c
- ld e,a
- pop bc
- ret
-
-2$: call div1
+ call div
jr nc,1$
-3$: add hl,de
- ld d,c
+ add hl,de
+1$: ld d,c
ld e,a
pop bc
ret
; the decrement can also be seen as compensating for the extra add hl,de that
; may be needed to make negative remainder positive before return to caller,
-; thus leaving things in a consistent state regardless of which exit occurred,
-; to find out if we need the extra add hl,de we can look for even return byte
+; thus leaving quotient in a consistent state regardless of which exit taken,
+; remainder needs the add hl,de if cf=1 returned (equiv. return byte is even)
; in the following code each sbc hl,de gets an inc a and each add hl,de gets
; a dec a, guaranteeing the integrity of the division, the initial scf/rla is
; be another shift between the scf/rla and increment/decrement so that the scf
; is implicitly in the 100s place, making the code awkward though it's correct
+; now optimized to only inc/dec a when doing zero-crossing, fix above analysis
+
+div: jr c,div1
div0:
push af
ld a,'A
rla
div00: adc hl,hl
sbc hl,de
- jr nc,1$
- add a,a
- inc a
+ jr nc,div01
+ dec a
jr div11
-1$: add a,a
- inc a
-div01: djnz div00
+div01: add a,a
+ djnz div00
+ dec a
or a
push af
ld a,'B
call print_word
ex de,hl
ld b,8
- scf
- rla
+ add a,a
div10: adc hl,hl
add hl,de
- jr nc,1$
- add a,a
- dec a
+ jr nc,div11
+ inc a
jr div01
-1$: add a,a
- dec a
-div11: djnz div10
- dec a ; compensation
+div11: add a,a
+ djnz div10
+ ;inc a
+ ;dec a ; compensation
scf
push af
ld a,'D