Search code examples
brainfuck

Sum of number in brainfuck


I would like to know if it is possible to calculate the sum of 1+2+3+...+k in brainfuck just with the number k at the beginning of the code?

For example is it possible to do 1+2+3 like this:

+++> (here the code creates a two add it with the three, create the one and add it)

Because I can do this : +++>++>+[<<+>>-]<[<+>-]< but if k=10000 how can I do this ?


Solution

  • Here is a simple version. Assume we name the first three cells y, temp0 and x. Then we can simply use this algorithm within a decrementing loop:

    +++           # Input number (in fisrt cell)
    [             # loop while first cell is not 0
     >[-]         # if second cell is null
     <[>>+<+<-]   # copy first cell in second and third and decrease it to 0
     >[<+>-]      # move second cell in first cell
     <-           # decrement input
    ]             # go to begin of while loop
    >>            # the current cell now has the result
    

    Note that this only works up to k = 22 due to the 8-bit limit. To output the number or deal with larger numbers, you'll have to use extra effort.