46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
from pathlib import Path
|
|
from .number import StreamNumber, LOG_DIR
|
|
|
|
def clear_logs():
|
|
if LOG_DIR.exists():
|
|
for p in LOG_DIR.glob("*"):
|
|
p.unlink()
|
|
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
def add(num_a: StreamNumber, num_b: StreamNumber) -> StreamNumber:
|
|
"""Digit-by-digit streamed addition."""
|
|
out_file = LOG_DIR / f"{num_a.hash}_add_{num_b.hash}.bin"
|
|
|
|
carry = 0
|
|
a_buf = list(num_a.stream(1))
|
|
b_buf = list(num_b.stream(1))
|
|
|
|
# align lengths
|
|
max_len = max(len(a_buf), len(b_buf))
|
|
a_buf = ["0"] * (max_len - len(a_buf)) + a_buf
|
|
b_buf = ["0"] * (max_len - len(b_buf)) + b_buf
|
|
|
|
with open(out_file, "wb") as out:
|
|
for i in range(max_len - 1, -1, -1):
|
|
s = int(a_buf[i]) + int(b_buf[i]) + carry
|
|
carry, digit = divmod(s, 10)
|
|
out.write(str(digit).encode())
|
|
if carry:
|
|
out.write(str(carry).encode())
|
|
return StreamNumber(out_file)
|
|
|
|
def sub(num_a, num_b):
|
|
"""Basic streamed subtraction (assumes a >= b)."""
|
|
# similar pattern with borrow propagation...
|
|
pass
|
|
|
|
def mul(num_a, num_b):
|
|
"""Chunked multiplication using repeated addition."""
|
|
# create temporary stage files for partial sums
|
|
pass
|
|
|
|
def div(num_a, num_b):
|
|
"""Long division, streamed stage by stage."""
|
|
# create multiple intermediate files: div_stage_1, div_stage_2, etc.
|
|
pass
|