Search code examples
brainfuck

Absolute of number in brainfuck


How would you go about getting the absolute of a number in brainfuck? I originally thought squaring the number ([->+>+<<]>>[-<<+>>]<<[>[->+>+<<]>>[-<<+>>]<<<-]) and square rooting it would work, but I can't think of a way to square root.


Solution

  • One way to compute the absolute of a number is to identify its sign. If you know how your program represents negative numbers, there is a reddit answer by /u/danielcristofani that explains that, in order to check for the sign of a number, you can

    double the number and see if it becomes zero in the process, e.g. with memory layout 0 0 x 0, this should work, producing 0 f 0 0 where f is the sign flag [>++[<]<[[-]+<+<]>>-]>[-]<

    If necessary, you should then apply an x = -x algorithm, for example its wrapping version:

    temp0[-]
    x[temp0-x-]
    temp0[x-temp0+]