brainfuck 中的数字总和

Sum of number in brainfuck

我想知道是否可以只用代码开头的数字k来计算brainfuck中1+2+3+...+k的和?

例如 1+2+3 是否可以这样:

+++>(这里的代码创建一个二加三,创建一个并添加它)

因为我可以这样做:+++>++>+[<<+>>-]<[<+>-]< 但是如果 k=10000 我该怎么做呢?

这是一个简单的版本。假设我们将前三个单元格命名为 ytemp0x。然后我们可以简单地在递减循环中使用 this 算法:

+++           # 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

请注意,由于 8 位限制,这最多只能工作到 k = 22。要输出数字或处理更大的数字,您将不得不付出额外的努力。

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

比Ingo的算法更简洁高效。使用三个 "slots"

  • |num|:原数;递减每个循环。
  • |temp|:复制回 |1|每个循环
  • |total|:每次循环累加值

    +++          input |num|
    [            while |num| is non-zero
      [>+>+<<-]    copy |num| to |temp| and |results|
      >-[<+>-]     copy |temp-1| back to |num|
      <            reset pointer
    ]
    >>.          output |total|
    
  • 相同的解释,但更详细

    +++          input |num|
    [            while |num| is non-zero
    
      [             until |num| is zero
        >+>+          increment |temp| and |total|
        <<            return to |num|
        -             decrement |num|
      ]
      >-           goto |temp|, decrement
      [<+>-]       until |temp| is zero; decrement |temp|; increment |num|
    
      <           goto |num|
    ]
    >>.          goto |total|, output it