The library had add, subtract (with a free compare in its carry), negate,
increment, decrement, multiply, and the bit ops -- but nothing that divides.
Asking for a decimal expansion without it means inlining a division per digit,
which is where the 11k character estimate came from.
clb_divmod N D Q W V T Ci X BUF leaves Q = N div D and N itself as the
remainder, eating D. Plain repeated subtraction:
Q = 0
while N >= D: N -= D ; Q += 1
Two things it took to get right:
* clb_sub_nc eats both operands, and the subtraction cannot alias (measured:
clb_sub_nc A B A Ci with A=15 B=10 gives 0), so each round needs copies of
N and D. Two of the three copies are pure overhead, but they are in the
loop body, which appears once.
* The first round has to be able to do nothing. Setting T = N and Q = -1
before the loop makes the first commit a no-op and lets the phantom count
cancel out, so the probe can live at the *bottom* of the loop and appear
only once. Without that the probe is duplicated and the tape grows by
about 1.3k.
5839 characters with a minimal driver (5845 with the two outputs), 9 cells,
all 76 sampled pairs correct in r8forge_byte_op_test. Runtime is O(N/D): the
worst case 2047/1 crosses the 5M step budget and hangs, so the test keeps
N/D <= 600 and SPEC says so. Division by zero is undefined, D >= 1 is the
caller's job.
Next: clb_digits on top of this, which needs a shared loop plus per-cell
conditional writes (computed addressing does not exist here) rather than four
copies of divmod.
23 lines
413 B
Plaintext
23 lines
413 B
Plaintext
%include "asm/divmod.r8asm"
|
|
|
|
; clb_divmod 的驱动:0 号 cell 放 X、1 号放 D,输出商和余数。
|
|
;
|
|
; r8forge_derive drv/divmod.r8asm -2 0=2047 1=10 # 204 7
|
|
; r8forge_derive drv/divmod.r8asm -2 0=7 1=10 # 0 7(零轮)
|
|
;
|
|
; out 依次是商、余数。
|
|
.var N 0
|
|
.var D 1
|
|
.var Q 2
|
|
.var W 3
|
|
.var V 4
|
|
.var T 5
|
|
.var Ci 6
|
|
.var X 7
|
|
.var BUF 8
|
|
|
|
clb_divmod N D Q W V T Ci X BUF
|
|
|
|
output Q
|
|
output N
|