Search code examples
brainfuck

Multiplication in Brainf*ck


I tried to write a brainfuck program which asks the user for two numbers (smaller than 10) to calculate the product of these numbers. After the calculation, it should print the result. My code looks like this:

    ++++[>++++[>+++<-]<-]   writing 48 / 0x30 / '0' in cell(2)
    ,>,>                    reading two numbers in cell(0) and cell(1)
    [<-<->>-]               decrementing cell(0) and cell(1) by 48 / 0x30 / '0'
    <<                      go to cell(0)
    [                       muliplication loop
        >                   go to cell(1)
        [>+>+<<-]           move cell(1) to cell(2) and cell(3)
        >>                  go to cell(3)
        [<<+>>-]            move cell(3) back to cell(1)
        <<<-                decrement cell(0)
    ]
    ++++[>++++[>+++<-]<-]   adding 48 / 0x30 / '0' to cell(2)
    >>.                     print result

This gives me really strange results:

0 * 1 = 3
1 * 1 = 4
1 * 2 = 8
2 * 1 = 5
2 * 2 = :

and so on.

Of course, the output actually looks like this:

1
1
4

but I wanted to show it more readable here.


Solution

  • After some consideration, I realized that I made a huge misstake when I modify the result to a printable number. I use cell(1)as a temporary counter cell, though it still has value in it. So I inserted >[-]< before adding 48 / 0x30 / '0' to the result:

        ++++[>++++[>+++<-]<-]   writing 48 / 0x30 / '0' in cell(2)
        ,>,>                    reading two numbers in cell(0) and cell(1)
        [<-<->>-]               decrementing cell(0) and cell(1) by 48 / 0x30 / '0'
        <<                      go to cell(0)
        [                       mulitplication loop
            >                   go to cell(1)
            [>+>+<<-]           move cell(1) to cell(2) and cell(3)
            >>                  go to cell(3)
            [<<+>>-]            move cell(3) back to cell(1)
            <<<-                decrement cell(0)
        ]
        >[-]<                   set cell(1) to 0 so that it can be used as counter
        ++++[>++++[>+++<-]<-]   adding 48 / 0x30 / '0' to cell(2)
        >>.                     print result
    

    note, that it still only works correctly with results smaller than 10