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.
2 Answers
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, producing0 f 0 0
wheref
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+]

- 75
- 5
We can do a bit better than that. Beginning with 0 x 0 0 with the pointer at x,
[<++[>->]>[[<-->-]>+>]<<]<[>>+<<--]
results in 0 0 |x| 0 with the pointer at the leftmost cell of the four. This assumes the number was in the usual two's complement representation, where 255 = -1 and 254 = -2 and so on (if cells are bytes). Which in turn assumes that in handling numbers up to this point, the program has been careful not to overflow past 127 or underflow past -128. Doable, but depending what's being done with these numbers it might be better to represent the sign separately from the beginning.

- 385
- 2
- 7