Code patternsArithmeticMultiply two cells

Multiply two cells

Multiplies two numbers that are both on the tape.

Watch it run

The form “x becomes x × y” works on 4 cells, named “x”, “y”, “scratch” and “counter”. Press Play, drag the step slider forwards and back, or change x and y with the sliders:

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

x × y is "add y, x times". The outer loop counts x down. Each round copies y into the answer (see copy a value).

It is a loop inside a loop. The inner loops are flat and cost one optimised step each, but the outer loop is not flat: its cost is a few steps for every unit of x.

That is fine for small numbers and hopeless for large ones. And a negative x on a wrapping cell is a very large number.

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 playground38 characters

What it needs

Common mistakes
  • Looping on the larger number. The cost follows the outer counter: put the smaller one there.
  • Forgetting that −3 on 32-bit cells means 4,294,967,293 rounds.

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
x becomes x × y13 to 16 × x × y3 + 4x
Adding the product to a third cellabout 18 × a × b2 + 5a
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
x becomes x × yx = 6; y = 783865627
x becomes x × yx = 15; y = 178383,57863
x becomes x × yx = 255; y = 255838849,6681,023
Adding the product to a third cella = 6; b = 785095932

Other forms

Adding the product to a third cell

acc gets a × b added; a and b are kept. This is the text the project generator writes. Layout: a, b, acc, two scratch cells.

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

The form “Adding the product to a third cell” works on 5 cells; the named ones are “a”, “b”, “acc” and “scratch”. Press Play, drag the step slider forwards and back, or change a and b with the sliders:

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.