Search

mercredi 8 février 2017

Sum numbers

Context

Brainfuck only allows increase / decrease values by 1.
So, to compute a sum A+B, we need to add 1 to A, and do it B times.

Initial state

  • Memory: A, B
  • Cursor: first cell
  • Input: any

Process

  • Move to B
  • While B cell is not null, decrease B and increase A by 1
    • Loop invariant: sum of both cells is A+B
    • When second cell equals 0, then first equals A+B
  • Move back to A

Code

>[-<+>]<

Final state

  • Memory: A+B, 0
  • Cursor: first cell
  • Input: any
  • Output: unchanged

Aucun commentaire:

Enregistrer un commentaire