A+B Problem/brainfuck

From Esolang
Jump to navigation Jump to search

The A+B Problem has seen many solutions in brainfuck, including:

Single-digits only (by User:None1)

,------------------------------------------------>,,------------------------------------------------[-<+>]<++++++++++++++++++++++++++++++++++++++++++++++++.

Both the input and the result have to be one-digit numbers, and the two numbers in the input are separated by exactly one character (space or any other).

A shorter version of the above, by the same author:

,>,,[<+>-]++++++[<-------->-]<.

8-bits only (0–255) (by User:None1)

This one uses algorithms mentioned in brainfuck algorithms.

[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]>>[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<[-<<<+>>>]<++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.

It only works on 8-bit cells, and the numbers in the input and the result should not exceed 255. The two numbers in the input are separated by line feeds.

32-bit integers only (0–4294967295) (by User:None1)

There is an awesome implementation that supports 32-bit integers. It is compiled from the Headache implementation, and because of its length, it is not shown here.

Arbitrary integers (by User:Timwi)

This implementation accepts any number of decimal integers separated by spaces. It will add them all up and output the result in decimal.

>,[-------------------------------->+<[>>+++++++++
  [>>>
    [<+>->[>]>[>]+[<]<[<]>]<<
    [->+<<]<-
  ]>>>[>]+[>]<-<[<]<<<<----------------
  [>>>>>[>]+[<]<<<<-]
>>]>[->>>>[-<<<<<+>>>>>>]<<<<+>>]<<-<,]>>>>>[-<<<<<+>>>>>>]<<----------<<<<
[
  [<]>->[>]>>+
    [>[+<-]<[->---------<<]>+>[<-]<[->---------->>+<]>]
  >[<<<]<
]
>>>>[>>>]<<<[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<<<]

In the first stage, characters are read from STDIN while an accumulated value is stored in unary on the tape. For each digit character, the accumulated value is multiplied by 10 and the character’s value added to it. For each space character, the accumulated value is appended to the previous accumulated value and a new one started. When input runs out, the result is available in unary. The second stage converts the unary number back into decimal, then converts digits to ASCII and outputs them.