sumbrainfuck

How can i add a+b in brainfuck?


How can i sum a and b without removing them?

;>;
<
[->>+>+<<<]
>
[->+>>+<<<]
>>
[<<<+>>>]
>
[<<<+>>>]
<<:

I have tried this, but "Error: Limit of operations (100000) reached before program finished!"


Solution

  • You need to move A and B at the same time as adding to C if you want to keep them.

    +++>        A (location 0) = 3
    ++++>       B (location 1) = 4
                C (location 2) = A plus B
    <<          goto A
    [>>+>+<<<-] add to C and location after C
    >           goto B
    [>+>>+<<<-] add to C and location after copy of A
    >           goto C
    

    Now your memory looks like this: 0, 0, C, A, B

    If you want to keep the original locations, you need to move the A and B values back to their original positions.

    >           goto copy of A
    [<<<+>>>-]  move to original A
    >           goto copy of B
    [<<<+>>>-]  move to original B