s LearnSqueak.com

INTEGER ALGORITHMS · POWERS

Exponentiation by squaring: build exact powers with fewer multiplications

Build and trace an integer power function in Squeak Smalltalk, halve the exponent, prove a loop invariant and test zero, negative bases and large exact results.

8 Workspace checkpoints438 exact assertionsNative halving replay

Before you start

Open a Workspace in native Squeak 6.1. Each checkpoint is a separate complete expression: copy one block, select all of that block and choose Print it. Its result should match the check beneath it. The longer checkpoints redefine their own block, so there is no invisible setup state. Do not concatenate all the checkpoints or file in the checkpoint collection.

Our contract is deliberately narrow: an integer base and a nonnegative integer exponent produce an exact integer. It does not implement roots, negative exponents, approximate real powers or a cryptographic routine. The empty product is one, so this function explicitly returns one for every exponent-zero input, including (0,0). That software convention does not resolve every mathematical use of 0 to power 0.

Review blocks and closures if value:value: is unfamiliar. Download the eight checkpoint expressions, the complete assertion expression, or the native source kit. No package installation or network connection is required to run the code.

01 · Start with a repeated product

A power with exponent 5 is five copies of the base multiplied together. Start from the multiplicative identity, one. This direct loop is our independent reference implementation.

Independent Workspace expression · select all, then Print it
| product |
product := 1.
5 timesRepeat: [product := product * 3].
product

Expected: 243

Check: Try zero repetitions: the untouched product is one.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Start with a repeated product, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

02 · Square a result instead of repeating the base

Squaring doubles the exponent represented by a factor: 3, 9, 81, 6561 represent powers 1, 2, 4, 8. Keep these exact integers, not floating-point approximations.

Independent Workspace expression · select all, then Print it
| factor powers |
factor := 3. powers := OrderedCollection with: factor.
3 timesRepeat: [factor := factor * factor. powers add: factor].
powers asArray

Expected: #(3 9 81 6561)

Check: Four stored factors can represent many different exponents.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Square a result instead of repeating the base, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

03 · Split an exponent into a parity bit and a quotient

For a nonnegative integer n, n = 2q + r with r either zero or one. Smalltalk sends odd as a unary message and // as integer division. Parentheses make our arithmetic intent explicit.

Independent Workspace expression · select all, then Print it
| n quotient remainder |
n := 13. quotient := n // 2.
remainder := n - (2 * quotient).
{n odd. quotient. remainder. (2 * quotient) + remainder}

Expected: {true. 6. 1. 13}

Check: 13 is odd, so keep one copy of the current factor before halving.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Split an exponent into a parity bit and a quotient, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

04 · Build a checked power block

Multiply the accumulator only for an odd remaining exponent. Halve that exponent every round and square the factor only if another round remains. The final unnecessary square is deliberately skipped.

Independent Workspace expression · select all, then Print it
| power |
power := [:base :exponent |
 | result factor remaining |
 (base isInteger and: [exponent isInteger and: [exponent >= 0]])
  ifFalse: [Error signal: 'Use an integer base and a nonnegative integer exponent'].
 result := 1. factor := base. remaining := exponent.
 [remaining > 0] whileTrue: [
  remaining odd ifTrue: [result := result * factor].
  remaining := remaining // 2.
  remaining > 0 ifTrue: [factor := factor * factor]].
 result].
power value: 3 value: 13

Expected: 1594323

Check: Read value:value: as one two-argument message sent to the block.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Build a checked power block, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

05 · Make the input contract visible

Negative bases are valid integer inputs. Negative or fractional exponents are outside this particular function. We choose the empty-product convention, including zero to exponent zero returning one.

Independent Workspace expression · select all, then Print it
| power |
power := [:base :exponent |
 | result factor remaining |
 (base isInteger and: [exponent isInteger and: [exponent >= 0]])
  ifFalse: [Error signal: 'Use an integer base and a nonnegative integer exponent'].
 result := 1. factor := base. remaining := exponent.
 [remaining > 0] whileTrue: [
  remaining odd ifTrue: [result := result * factor].
  remaining := remaining // 2.
  remaining > 0 ifTrue: [factor := factor * factor]].
 result].
{power value: 0 value: 0. power value: -2 value: 5. power value: -2 value: 6}

Expected: #(1 -32 64)

Check: The signs alternate for a negative base; zero exponent bypasses the loop.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Make the input contract visible, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

06 · Record each algorithm state

Each row contains result, factor and remaining exponent. The initial row comes before the loop. The final factor remains 6561 because there is no next iteration that needs its square.

Independent Workspace expression · select all, then Print it
| result factor remaining trace |
result := 1. factor := 3. remaining := 13.
trace := OrderedCollection with: {result. factor. remaining}.
[remaining > 0] whileTrue: [
 remaining odd ifTrue: [result := result * factor].
 remaining := remaining // 2.
 remaining > 0 ifTrue: [factor := factor * factor].
 trace add: {result. factor. remaining}].
trace asArray

Expected: {#(1 3 13). #(3 9 6). #(3 81 3). #(243 6561 1). #(1594323 6561 0)}

Check: The remaining values are 13, 6, 3, 1 and 0: four rounds.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Record each algorithm state, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

Watch the accumulator earn its answer

NATIVE SQUEAK CAPTURE
Native Squeak binary exponentiation table, starting at result 1, factor 3 and exponent 13
Five genuine Morphic captures replay the computed states. Green marks the current row; this is a captured-state replay, not mouse footage.

The table comes from the same loop as checkpoint 6. Each tuple is ordered as {result. factor. remaining}. Follow the green row: an even remaining exponent leaves the result unchanged, while an odd one consumes one factor. Halving eventually reaches zero.

Download the native visual expression. Open it as text and Do it as a whole. Change stage := 0. to a value from 1 through 4 and close the old window before opening the next state. It is a fixed 1000 × 520 window, with no timer or saved state. The renderer displays rows computed by the arithmetic loop; it does not hard-code the answers.

07 · Count multiplications, not milliseconds

Use counters to distinguish accumulator multiplications from factor squarings. This exact count is a structural property of this implementation, not a timing benchmark.

Independent Workspace expression · select all, then Print it
| result factor remaining products squares |
result := 1. factor := 3. remaining := 13.
products := 0. squares := 0.
[remaining > 0] whileTrue: [
 remaining odd ifTrue: [result := result * factor. products := products + 1].
 remaining := remaining // 2.
 remaining > 0 ifTrue: [factor := factor * factor. squares := squares + 1]].
{result. products. squares. products + squares}

Expected: #(1594323 3 3 6)

Check: Six multiplications here replace thirteen in our initial repeated-product loop.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Count multiplications, not milliseconds, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

08 · Keep a large result exact

Squeak grows its integer representation as needed. There is no conversion to Float in our function. Large results still cost time and memory: fewer multiplications do not make arbitrarily large answers cheap.

Independent Workspace expression · select all, then Print it
| power |
power := [:base :exponent |
 | result factor remaining |
 (base isInteger and: [exponent isInteger and: [exponent >= 0]])
  ifFalse: [Error signal: 'Use an integer base and a nonnegative integer exponent'].
 result := 1. factor := base. remaining := exponent.
 [remaining > 0] whileTrue: [
  remaining odd ifTrue: [result := result * factor].
  remaining := remaining // 2.
  remaining > 0 ifTrue: [factor := factor * factor]].
 result].
power value: 2 value: 100

Expected: 1267650600228229401496703205376

Check: Compare the entire integer, not a rounded scientific-notation display.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Keep a large result exact, showing its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was evaluated from the displayed code.

Explain what stays true

At the beginning of every iteration, result × factorremaining = originalBaseoriginalExponent. This is a statement about the current state, not a line that our loop has to evaluate. Initially result is one, factor is the original base and remaining is the original exponent, so the statement holds.

Write the positive remaining exponent as 2q + r, where r is zero or one. When r is one, multiplying result by factor accounts for that one extra copy. The q remaining pairs are represented by replacing factor with its square and remaining with q. If q is zero, the factor is no longer needed and we skip squaring it. In either case the represented total stays unchanged. These integer equalities also work for negative bases.

The nonnegative remaining exponent strictly decreases whenever it is positive: integer division by two makes it smaller. Thus the loop terminates. At zero, the factor contributes the multiplicative identity, leaving result equal to the required answer. For our chosen all-zero-input convention, the loop is skipped entirely. Checking initialization, preservation and termination is more informative than merely observing several successful examples.

Count the right kind of work

For positive exponent n with k binary digits, this implementation has k loop rounds. It performs k − 1 factor squarings and one accumulator multiplication for each one-bit of n. For 13 (binary 1101), that is three squarings and three accumulator multiplications. For zero there are no rounds and no multiplications. This exact accounting belongs to this implementation: another valid power routine can avoid multiplying by one or choose a different traversal.

The multiplication count grows logarithmically with n, rather than linearly as in our reference loop. That does not mean logarithmic wall-clock time regardless of the input. Integer operands grow, and multiplying large integers costs more than multiplying small ones. The output itself can be enormous. Our loop holds a fixed number of integer references, not a fixed number of bytes. A trace allocates additional collections and is intentionally a teaching tool, not the minimal-storage version.

No speedup was measured here. If you need a performance claim, use the measurement workflow, compare equivalent contracts and include representative input sizes. Do not use this branch-dependent teaching code for secret cryptographic exponents: it offers no constant-time guarantee.

Test independently and inspect failures

The downloadable test expression first evaluates all eight exact published checkpoints. It then checks every integer base from −8 through 8 at every exponent from 0 through 24 against a separate repeated-multiplication oracle: 425 comparisons. Three further checks reject a negative exponent, a fractional exponent and a Float base. Two large-result checks cover 10 to power 80 and a negative base raised to an odd exponent, −3 to power 101. The total is 438 direct assertions, not a claimed SUnit suite.

Open the tests as text, select the whole expression and Print it. Expect 438; a mismatch signals an Error. The oracle uses repetition rather than halving, so it is less likely to share an exponent-update bug with our function. A passing finite grid is evidence, not a proof for all integers. The invariant supplies the reasoning beyond that grid.

If an answer is wrong, inspect the state before the update. Squaring factor before consuming its odd copy changes the meaning of that copy. Replacing integer division with ordinary / makes odd exponents fractional instead of shrinking through integers. Forgetting the exponent contract can create a superficially plausible result for invalid input: a negative exponent simply skips the loop and would incorrectly return one.

Extend the idea without hiding the contract

  1. Change the trace to base −2 and exponent 7. Predict every sign before running it. Keep the input pair, result and explanation synchronized.
  2. Return both the answer and an operation-count record from a new block. Test exponent zero, one, a power of two and one less than a power of two.
  3. Extract the checked block into a class-side method and translate the grid tests into SUnit. Preserve explicit invalid-input tests instead of silently accepting a wider numeric domain.
  4. As a separate exercise, reduce after every multiplication using a positive integer modulus. Write down that new contract first; compare its small cases with exact powers followed by a remainder. Do not present the result as a security library.

Exact powers, Horner evaluation and Euclid’s algorithm all use compact state, but preserve different mathematical facts. Naming the invariant is what makes each state update understandable.

Sources and next steps

SICP Comparison Edition, section 1.2.4: Exponentiation presents successive squaring and contrasts its operation growth with repeated multiplication. Reviewed 28 October 2026. This lesson’s checked iterative Smalltalk implementation, checkpoint progression, exhaustive grid, exact counts and native visualization are original. The official Squeak documentation is the environment reference.

Continue with integer bitsets to work directly with binary membership, or exact Fractions before designing a separate negative-exponent contract. Keeping this lesson integer-only makes its rejection rules and exact results easy to verify.