Carry normalization of a digit array 2026-10-31
Process a digit-array integer representation from low to high positions. The integer division supplies and . Replacing the current digit by and adding to the next position preserves the represented value. Append zero storage when a positive carry leaves the allocated array. The processed prefix remains normalized and the value stays fixed.
This also works with signed temporary digits when the represented value is nonnegative. A negative carry cannot leave the final allocated position: the normalized lower digits represent a value less than that position's next radix power, which could not offset that negative carry. Positive carries eventually stop beyond the value's finite radix expansion. Thus the usual nonnegative-digit algorithm admits this useful extension without interpreting truncated division as floor division.
Allocate a fresh array and copy every digit:
function CopyNum(n: number): number
new(result, len(n))
for i := 0 to len(n)-1 do
result[i] := n[i]
return resultEvery coefficient in the digit-array integer representation is unchanged, so the value is unchanged. The new array shares no storage with
n; assigning one pointer to the other would instead create reference aliasing. Since the entries are integers, copying the entries also gives the required deep copy of this representation.The pointer argument must be passed by reference, because it is replaced:
procedure Lengthen(var n: number)
old := n
L := len(old)
new(result, 2*L)
for i := 0 to L-1 do
result[i] := old[i]
for i := L to 2*L-1 do
result[i] := 0
n := resultThe low-order coefficients are preserved and the newly allocated high-order coefficients are zero, so the digit-array integer representation has the same value. The allocation remains nonempty because . Neither allocation nor an uninitialized high-order cell may be assumed to contain zero. Any other reference to the old array still denotes that old array; the code does not free storage through an alias.
function Add(a, b: number): number
L := max(len(a), len(b))
new(result, L)
for i := 0 to L-1 do
result[i] := 0
if i < len(a) then result[i] := result[i] + a[i]
if i < len(b) then result[i] := result[i] + b[i]
Normal(result)
return resultBy the digit-array integer representation, the raw result has value . Carry normalization of a digit array produces a normalized result, including any final carry. Both input arrays remain unchanged, so the operation also works when
a and b alias each other.