How to calculate the sum of 2 numbers with BrainFuck

前端 未结 7 753
独厮守ぢ
独厮守ぢ 2020-12-09 06:01

I\'m trying to write a program with BrainFuck that can read two numbers up to 9, calculate the sum of them and then print the result out, e.g. 3 & 5 give the result 8 .

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 06:37

    I built a code that will work with an infinite amount of input numbers but it can only output 1 or 2 digits so the range of the sum of digits can be 0-99

    >,                     go to cell #1 and read input
    [                      loop while input is not null
      >+++++++[<------->-] subtract 49 from input
      <+                   add 1 to input so we have the value of the input numeral in cell #1
      [-<+>]               add cell #1 to cell #0
      ,                    read next numeral
    ]                      repeat until no number is being input (the input number can be longer than two digits)
    >-                     go to cell #2 and set it to minus 1 so the loop will run (i will explain that at the end of the loop)
    [                      loop while number in cell #0 is greater than 9
      +                    set the value of #2 to 0
      <[->+>+<<]           copy the value of #1 to #2 and #3
      >>[-<<+>>]           copy the value of #3 back to #1
      <<<                  go to #0
      [->>>+>+<<<<]        copy it to #3 and #4
      >>>>[-<<<<+>>>>]     restore it in #0
      <                    go to 3
      [-[-[-[-[-[-[-[-[-[  check if number is greater than 9
      <<+<----- ----->>>   if yes increment number in cell #1 and decrease number in cell #0 by 10
      [-]]]]]]]]]]]        set #3 to 0 so we can leave the loop
      <<                   go to #1
                           we need to check if the number in cell #1 was incremented
                           cell #2 will store the most recent value of cell #1
      [->->+<<]            so we subtract the value of cell #2 by the value of cell #1 and 
                           store the value of cell #1 in cell #3
      >>[-<<+>>]           restore the value of #1
      <                    go back to cell #2
    ]                      if cell #1 was increased then cell #2 will be minus 1 and the loop will restart
    <[>+++++++[<+++++++>-] if cell #1 is greater than 0 then add 49 to it
    <-.[-]]                subtract 1 so we have the ascii code of the value in #1 then print it and set it to zero
    +++++++[<+++++++>-]<-. do the same with the value in cell #0
    

    or in short:

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

提交回复
热议问题