Complaint received and agreed with: nine cells to pass for a division is not an
interface anybody wants to type. Two things made it possible to shrink:
* .tp and macro arguments accept address expressions (measured: .tp A+1
assembles, and set_0 A+1 expands to .tp A+1 inside the callee). So the
four scratch cells can be passed as one block: clb_divmod N D Q S uses S,
S+1, S+2 and S+3.
* BUF and X were unnecessary: copy already has sources and destinations to
spare that are dead at the moment they are needed, and clb_inc_ip can take
a cell that the probe is about to overwrite.
So the signature is now clb_divmod N D Q S -- three data cells and one scratch
base -- and the tape dropped from 5839 to 4189 characters on the way, because
the scratch cells now sit next to each other and every .tp walk got shorter.
Still correct: all 76 sampled pairs (2047/10 = 204 7, 7/10 = 0 7, 10/10 = 1 0,
1234/100 = 12 34, 999/7 = 142 5, 2047/2047 = 1 0), and the O(N/D) limit is
unchanged.
82 lines
2.6 KiB
Plaintext
82 lines
2.6 KiB
Plaintext
%include "asm/raw_sub_nc.r8asm"
|
|
%include "asm/add_ip.r8asm"
|
|
|
|
; 除法/取模:Q = N div D,R 就是 N 自己。
|
|
;
|
|
; 用它自己那句老话:**只有纸带长度是目标**。所以这里不写长除法的移位/恢复,
|
|
; 就是最钝的那招:
|
|
;
|
|
; Q = 0
|
|
; while N >= D: N -= D ; Q += 1
|
|
;
|
|
; 循环体在纸带里只出现一次,长度和 N、D 的大小无关;代价是运行 O(N/D)
|
|
; (N=2047、D=1 时约 2047 轮,会撞 500 万步上限,所以 N/D 别超过 1500 左右)。
|
|
;
|
|
; 三个关键点,都是踩出来的:
|
|
;
|
|
; 1. **`clb_sub_nc` 会把 N 和 D 都吃掉**,而减法不能用 `S == A` 的别名
|
|
; (实测 `clb_sub_nc A B A Ci` 直接给出 0)。所以每轮都要 copy 出 v = N、
|
|
; d = D 再减 —— 三个 copy 里有两个是给它交的"过路费"。
|
|
;
|
|
; 2. **首轮要能"什么都不做"**:把 t 预置成 N,Q 预置成 -1。于是第一轮的
|
|
; "提交 t -> N" 是空操作,"Q += 1" 正好把 -1 补回 0;探测放在循环体末尾,
|
|
; 所以 `N < D`(零轮)和 `N == D`(一轮)都对,而且探测代码只出现一次。
|
|
; 没有这个技巧就得在循环外面再写一遍探测,纸带多 1.3k。
|
|
;
|
|
; 3. **草稿只要一个基址**:`.tp` 和宏实参都接受地址表达式(`S+1` 能编译),
|
|
; 所以 4 个草稿格当一块传进来就行,不用一个一个列。
|
|
;
|
|
; 除零没有定义:调用者保证 D >= 1,这里不检查(D = 0 会一直循环)。
|
|
|
|
; Macro clb_divmod
|
|
; %1: Cell N
|
|
; %2: Cell D
|
|
; %3: Cell Q
|
|
; %4: Cell S
|
|
;
|
|
; N 是被除数,结束时就是余数 R;D 是除数,会被吃干净;Q 是商(宏自己清零后累加)。
|
|
; S 起的 4 个**连续** cell 是草稿(S、S+1、S+2、S+3),进来时要求是干净的。
|
|
; 前提 D >= 1(除零没有定义,这里不检查)。
|
|
%macro clb_divmod 4
|
|
.anchor before_clb_divmod
|
|
|
|
; s = %4,s+1 = %4+1 ... 四个草稿格
|
|
; s : N 的副本
|
|
; s+1 : D 的副本
|
|
; s+2 : 减法结果 / 拷贝缓冲
|
|
; s+3 : 进位(= N >= D)
|
|
|
|
; Q = -1:第一轮的 +1 把它补回 0
|
|
erase %3
|
|
clb_dec_ip %3 %4
|
|
|
|
; t = N:第一轮"提交"是空操作
|
|
.tp %1
|
|
copy %4+2 %4
|
|
|
|
; Ci = 1 只为让底下那个 biz 直接进循环体;
|
|
; 真正的判断在体尾的 clb_sub_nc 里
|
|
.tp %4+3
|
|
set_1
|
|
|
|
biz
|
|
; ---- 体:提交上一轮减出来的 t,记一个商,再探一次
|
|
.tp %4+2
|
|
copy %1 %4 ; N = t
|
|
|
|
clb_inc_ip %3 %4+1 ; Q += 1
|
|
|
|
.tp %1
|
|
copy %4 %4+2 ; s = N
|
|
.tp %2
|
|
copy %4+1 %4+2 ; s+1 = D
|
|
.tp %4+3
|
|
set_1 ; 进位入 = 1,做的是普通减法
|
|
clb_sub_nc %4 %4+1 %4+2 %4+3 ; t = N - D,Ci = (N >= D)
|
|
|
|
.tp %4+3
|
|
rnz
|
|
|
|
.tp before_clb_divmod
|
|
%endmacro
|