Shadock - 4 months ago 34

Brainfuck Question

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:

`+++>`

Because I can do this :

`+++>++>+[<<+>>-]<[<+>-]<`

Answer

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.