2

コードの先頭にある番号 k だけで、brainfuck で 1+2+3+...+k の合計を計算できるかどうか知りたいですか?

たとえば、次のように 1+2+3 を行うことは可能ですか?

+++>(ここで、コードは 2 つを作成し、それを 3 つに追加し、1 つを作成して追加します)

私はこれを行うことができるので:+++>++>+[<<+>>-]<[<+>-]<しかし、k=10000の場合、どうすればこれを行うことができますか?

4

2 に答える 2

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

Ingo のアルゴリズムよりも簡潔で効率的なアルゴリズム。3つの「スロット」を使用

  • |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
    
于 2015-02-14T22:41:37.903 に答える