Code patternsArithmeticPowers of two, and powers

Powers of two, and powers

Works out 2 to the power n, or x to the power y.

Watch it run

The form “2 to the power n” works on 3 cells, named “n”, “result” and “scratch”. Press Play, drag the step slider forwards and back, or change n with the slider:

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

Start at 1 and double it n times. Doubling is multiplying by the constant 2 (see multiply by a constant), into a scratch cell and back.

A general power is the same loop round a multiplication (see multiply two cells) instead of a doubling.

Doubling a number moves all its bits one place up. On a wrapping cell the top bit falls out. That is the idea the bit peel turns into a tool.

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

What it needs

Common mistakes
  • Expecting 0 to the power 0 to be 0. The loop never runs, so the answer is the 1 it started with.
  • Leaving the base behind: the general form keeps a copy of x in a scratch cell and must clear it at the end. The snippet on the wiki does not.

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
2 to the power ngrows with 2ⁿ2 + 4n
x to the power ygrows with the resultgrows with the result ÷ x
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
2 to the power nn = 082342
2 to the power nn = 582354022
2 to the power nn = 128232,90050
x to the power yx = 3; y = 48632,643181
x to the power yx = 2; y = 58631,605149

Other forms

x to the power y

Layout: x, y, three scratch cells. x becomes the result.

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

The form “x to the power y” works on 5 cells, named “x”, “y”, “base”, “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.

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.