Shadock Shadock - 9 months ago 105
Brainfuck Question

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 ?


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
[             # loop while this is not 0
 >[-]         # addition algorithm
 <[>>+<+<-]   # addition algorithm
 >[<+>-]      # addition algorithm
 <-           # decrement input
>>            # 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.