s LearnSqueak.com

INTEGER ALGORITHMS · DIVISIBILITY

Euclid’s algorithm: find a greatest common divisor with remainders

Build and trace an exact integer GCD in Squeak Smalltalk, explain why remainders preserve the answer, and test signs, zero, large integers and ratio reduction.

8 Workspace checkpoints452 exact assertionsNative remainder replay

Before you start

Use a native Squeak 6.1 Workspace. Each checkpoint below is a separate, complete expression: select all of that code block and choose Print it. Do not join the eight blocks together or file in the whole checkpoint collection. No extra package or network connection is needed. Review blocks and closures and collections if the iteration messages are new.

This is an algorithm workshop about exact integer divisibility. It complements, rather than replaces, the Fraction Lab. We implement the recurrence ourselves so that state changes, contracts and a correctness argument are visible.

Download the eight checkpoint expressions, the 452-assertion test expression, or the complete native source kit.

01 · Find common divisors the slow way

If two lengths are 48 and 18 units, the largest whole-number tile size that divides both is 6. First enumerate candidates so that the meaning of the answer is concrete. The backslash-pair message returns the remainder: a divisor leaves zero. The interval starts at one because division by zero is not a candidate test. This small-input baseline will later serve as a separate testing oracle, not as our production algorithm.

Independent Workspace expression · select all, then Print it
| common |
common := (1 to: 18) select: [:candidate |
 ((48 \\ candidate) = 0) and: [(18 \\ candidate) = 0]].
{common asArray. common last}

Check: Expect the divisors 1, 2, 3, 6 and the greatest value 6. Trying all candidates scales with the smaller input’s magnitude; avoid this baseline for huge numbers.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Find common divisors the slow way, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

02 · Replace division by one remainder step

Integer division expresses 48 as two groups of 18 plus a remainder of 12. Any number dividing both 48 and 18 divides 12, because 12 is 48 minus two times 18. Conversely, a divisor of 18 and 12 divides 48. Therefore the common divisors are unchanged when the pair (48, 18) becomes (18, 12). This preserved property is the loop invariant. Parentheses are important: Smalltalk binary messages share one precedence level.

Independent Workspace expression · select all, then Print it
| a b quotient remainder |
a := 48. b := 18.
quotient := a // b.
remainder := a \\ b.
{quotient. remainder. a = ((quotient * b) + remainder)}

Check: Expect #(2 12 true). For positive b, the remainder is at least zero and less than b; that shrinking second value supplies the termination argument.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Replace division by one remainder step, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

03 · Write the complete iterative block

The block validates that both inputs are integers, normalizes signs with abs, and repeats the remainder transformation until b is zero. Save the remainder before assigning a, or the old dividend is lost. At termination, every positive divisor of a also divides zero, so the remaining a is the result. The block deliberately returns zero for the all-zero input as a programming convention; zero is not a largest positive divisor of zero.

Independent Workspace expression · select all, then Print it
| gcd |
gcd := [:left :right |
 | a b remainder |
 (left isInteger and: [right isInteger])
  ifFalse: [Error signal: 'GCD needs integers'].
 a := left abs. b := right abs.
 [b ~= 0] whileTrue: [
  remainder := a \\ b.
  a := b. b := remainder].
 a].
gcd value: 48 value: 18

Check: Expect 6. Each keyword pair value:value: sends two arguments to the same block. The local a and b do not modify the original integer objects.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Write the complete iterative block, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

04 · Record each pair as an independent snapshot

A trace makes accidental assignment errors visible. Start with the original pair, then add a newly allocated two-element array after each transformation. Do not keep inserting one mutable array and changing its elements: every trace entry would point to the same changing object. The trace is diagnostic storage; the plain loop only needs a, b and the remainder.

Independent Workspace expression · select all, then Print it
| a b remainder trace |
a := 48. b := 18.
trace := OrderedCollection with: {a. b}.
[b ~= 0] whileTrue: [
 remainder := a \\ b.
 a := b. b := remainder.
 trace add: {a. b}].
trace asArray

Check: Expect four pairs ending in #(6 0). Do not perform another remainder operation after reaching zero; the loop condition prevents division by zero.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Record each pair as an independent snapshot, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

Watch the pair shrink

NATIVE SQUEAK CAPTURE
Native Squeak GCD trace highlighting the initial pair 48 and 18
Four genuine Morphic captures replay the computed pairs (48,18), (18,12), (12,6) and (6,0). This is a captured-state replay, not mouse footage.

Download the native visual trace expression, open it as text in Squeak and Do it as a whole. Change stage := 0. to 1, 2 or 3 for later states; close the previous window before opening the next. Its fixed layout needs 1000 × 480 pixels. It has no timer, network access or saved application state. Green highlights the current pair while uncomputed rows remain concealed.

05 · Specify sign and zero behavior

Callers should not need to guess edge cases. This API always returns a nonnegative integer: changing an input’s sign does not change its divisors. One zero input returns the other input’s absolute value. Two zeros return zero under our explicit convention. In mathematical discussions that define GCD as the greatest positive common divisor, the all-zero case must be treated separately. We keep a stable software contract rather than hiding that distinction.

Independent Workspace expression · select all, then Print it
| gcd |
gcd := [:left :right |
 | a b remainder |
 (left isInteger and: [right isInteger])
  ifFalse: [Error signal: 'GCD needs integers'].
 a := left abs. b := right abs.
 [b ~= 0] whileTrue: [
  remainder := a \\ b.
  a := b. b := remainder].
 a].
{gcd value: -48 value: 18.
 gcd value: 0 value: -18. gcd value: 0 value: 0}

Check: Expect #(6 18 0). Try reversing the arguments: (18, 48) takes an extra initial transformation but produces the same result.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Specify sign and zero behavior, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

06 · Reject rounded input; retain large exact integers

This implementation is an integer algorithm, not an approximate calculation. Passing 3.5 is an error, not an invitation to silently round. Squeak can represent integers larger than a machine-sized SmallInteger, so multiply both inputs by 10 raised to the twentieth power and retain an exact result. LargeInteger arithmetic has real cost; fewer remainder steps does not mean that arithmetic on enormous values is free.

Independent Workspace expression · select all, then Print it
| gcd scale rejected |
gcd := [:left :right |
 | a b remainder |
 (left isInteger and: [right isInteger])
  ifFalse: [Error signal: 'GCD needs integers'].
 a := left abs. b := right abs.
 [b ~= 0] whileTrue: [
  remainder := a \\ b.
  a := b. b := remainder].
 a].
scale := 10 raisedToInteger: 20.
rejected := [gcd value: 3.5 value: 2. false]
 on: Error do: [:error | true].
{gcd value: (48 * scale) value: (18 * scale). rejected}

Check: Expect the exact integer 600000000000000000000 and true. The Error handler is a contract demonstration; production callers should normally validate or handle invalid input at their boundary.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Reject rounded input; retain large exact integers, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

07 · Reduce a ratio without constructing a Float

A GCD is useful when normalizing a pair of integer measurements. Divide both components of 1920 by 1080 by their GCD, obtaining 16 to 9. Use integer division because the GCD divides both inputs exactly. Squeak already reduces Fraction objects for ordinary fraction arithmetic; this example is for keeping an explicit pair, such as image dimensions, rather than replacing the Fraction implementation.

Independent Workspace expression · select all, then Print it
| gcd width height divisor |
gcd := [:left :right |
 | a b remainder |
 (left isInteger and: [right isInteger])
  ifFalse: [Error signal: 'GCD needs integers'].
 a := left abs. b := right abs.
 [b ~= 0] whileTrue: [
  remainder := a \\ b.
  a := b. b := remainder].
 a].
width := 1920. height := 1080.
divisor := gcd value: width value: height.
{width // divisor. height // divisor}

Check: Expect #(16 9). Define your application’s rules for zero or negative dimensions before using this pattern. The pair #(0 0) would need special handling because its divisor under our convention is zero.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Reduce a ratio without constructing a Float, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

08 · Fold several measurements into one GCD

For more than two integers, combine the accumulated GCD with each next value. Starting at zero is convenient because gcd(0, n) is the absolute value of n. For 84, 126 and 210, the running answers are 84, 42 and 42. This is a reduction, not sorting or pairwise comparison of every combination. The empty collection also returns zero under the chosen seed convention, which should be documented if exposed as an API.

Independent Workspace expression · select all, then Print it
| gcd measurements |
gcd := [:left :right |
 | a b remainder |
 (left isInteger and: [right isInteger])
  ifFalse: [Error signal: 'GCD needs integers'].
 a := left abs. b := right abs.
 [b ~= 0] whileTrue: [
  remainder := a \\ b.
  a := b. b := remainder].
 a].
measurements := #(84 126 210).
measurements inject: 0 into: [:answer :next |
 gcd value: answer value: next]

Check: Expect 42. Add a value coprime to 42 and watch the result become 1. Once the accumulator is 1, no later integer can make the common divisor larger.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Fold several measurements into one GCD, with evaluated result selected
Actual Squeak 6.1 Workspace after Print it. The selected result was computed by the displayed expression.

Why this loop terminates with the right answer

The invariant is equality of the sets of common divisors before and after each transformation. Writing a = qb + r proves both directions: a common divisor of a and b divides r, and a common divisor of b and r divides a. Normalizing both inputs to nonnegative integers makes the remainder argument straightforward. Whenever b is positive, the next b is smaller and nonnegative. An infinite strictly decreasing sequence of nonnegative integers is impossible.

When b reaches zero, the remaining positive a is the greatest divisor common to a and zero. If both original inputs were zero, the loop never runs and our documented software convention returns zero instead. Separate that convention from the greatest-positive-divisor definition. The loop condition is also a safety condition: it prevents evaluating a remainder with zero as divisor.

Check against an independently written oracle

The downloadable test expression evaluates all eight exact published checkpoints, then checks every ordered pair in −10 through 10 against a slow divisor-enumeration oracle. That is 441 pair comparisons, including signs, reversed pairs, equal values and all zero cases. Three further checks cover a coprime Fibonacci pair, a large integer divisible by three, and rejection of a noninteger Fraction. Together these are 452 direct assertions, not a claimed SUnit suite.

Open the tests as text, select the entire expression, and Print it. Expect 452; any mismatch signals an Error. The small exhaustive grid catches many assignment and boundary bugs, but it is not a proof over all integers. The invariant and termination argument provide the reasoning that the finite tests cannot.

Understand the savings without inventing a benchmark

The remainder version skips many individual subtraction steps. For example, when one input greatly exceeds the other, one remainder operation replaces repeated subtraction. The number of Euclidean iterations grows logarithmically with the smaller positive input; consecutive Fibonacci inputs are a useful demanding family. The SICP comparison edition’s GCD discussion explains the Fibonacci connection. That statement counts iterations, not constant-cost CPU instructions. Integer remainder becomes more expensive as the operands gain digits.

The core loop keeps a fixed number of integer references. Its integers still occupy storage proportional to their digit lengths. The optional trace allocates one pair per iteration, so it is intentionally not a constant-storage implementation. Do not claim measured speedups from these structural observations: use the site’s measurement workflow with representative inputs if runtime is the question.

Extend the lab carefully

  1. Instrument the block with a remainder-operation counter. Compare (144,89), (144,1), and their reversed pairs without changing the result contract.
  2. Extract the block into a class-side method and turn selected direct assertions into SUnit tests. Keep the argument validation and all-zero convention explicit.
  3. Build a ratio-normalization function that rejects invalid dimensions before dividing. Test (0,0), (0,1080), negative dimensions and nonintegers according to your chosen application contract.

Keep arithmetic, validation and presentation separate. The visualization should display values calculated by the algorithm rather than implementing a different algorithm inside the drawing code.

Sources and next steps

The University of British Columbia PLP chapter on greatest divisors and the Euclidean algorithm supplies the mathematical definition, remainder argument and discussion of zero conventions. Reviewed 27 October 2026. This lesson’s Smalltalk checkpoints, exhaustive test grid and Morphic trace are original. The official Squeak documentation is the environment reference.

Continue with exact Fractions, the prime sieve or Horner’s running-result algorithm. Finding a GCD does not require first factoring both numbers into primes; that is the useful distinction to carry forward.