ASCIIThenANSI - 6 months ago 25

Brainfuck Question

In BF, I know you can add and subtract with the

`+`

`-`

`Multiply 4 and 4`

++++[>++++<-]

But how can I multiply two variables, or use other mathematical operators, such as modulo or division?

Answer

Here is a generic looking routine to multiply two numbers in bf. Taken from here.

Multiply a value by another value This requires multiple copies and nested loops.

```
Copy first operand to a work location
Move to work location and enter a loop
Move to second operand and copy to a work location
Move to second work location and enter a loop
Move to result location and increment
Move to second work location and decrement
Loop until second work location equals zero
Move to first work location and decrement
Loop until first work location equals zero
```

Example:

Multiply three (a[p]) times five (a[p+1]) and place the result in a[p+2].

```
+++>+++++<
[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<
[<<
[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<
[<<+>>-]
<-]
```

Some further reading here