Code patternsArithmeticSquare

Square

Replaces a number by its square.

Watch it run

The form “As a sum of odd numbers” works on 3 cells, named “x”, “counter” and “scratch”. Press Play, drag the step slider forwards and back, or change x with the slider:

The figure needs JavaScript. The program below is the result for the example values.

A square is a sum of odd numbers: 1 + 3 + 5 + 7 = 16 = 4 × 4. The loop counts down from x and each round adds the next odd number, two for every unit still left plus one.

The other way is plain: copy x and multiply the two (see copy a value and multiply two cells).

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

[->+<]>[-[->+<<++>]<+>>[-<+>]<]<
Open in the playground32 characters

What it needs

Common mistakes
  • Expecting the square of 16 or more to fit an 8-bit cell: 16 × 16 = 256 wraps to 0.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
As a sum of odd numbersabout 7 × x × x3 + 5x
Copy, then multiply13 to 20 × x × x6 + 4x
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
As a sum of odd numbersx = 583221428
As a sum of odd numbersx = 158321,68478
As a sum of odd numbersx = 255832456,9641,278
Copy, then multiplyx = 586451226

Other forms

Copy, then multiply

Layout: x, copy, two scratch cells.

[->+>+<<]>>[-<<+>>]<<[->>>+<<<]>>>[<<[-<+>>+<]>[-<+>]>-]<<<>[-]<
Open in the playground64 characters
Run this form step by step

The form “Copy, then multiply” works on 4 cells, named “x”, “copy”, “scratch” and “counter”. Press Play, drag the step slider forwards and back, or change x with the slider:

The figure needs JavaScript. The program below is the result for the example values.

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.