Jay Bosamiya - 1 year ago 140

Brainfuck Question

Given that a number in the 0th cell of tape is filled and the rest are all just used as scratch cells (i.e. they all start at 0 and are temporaries -- I don't care what happens to them), I would like to replace the 0th cell with a 0 or a 1. 0 if even, 1 if odd.

Basically, what I want to do is (in C-esque pseudocode):

`cell[0] = (cell[0] % 2)`

I know that there exists a divmod algorithm defined as follows:

If one does not need to preserve n, use this variant:

`# >n d`

[->-[>+>>]>[+[-<+>]>+>>]<<<<<]

# >0 d-n%d n%d n/d

However, since

`X % 2 == X & 1`

Is there any better algorithm/technique for finding out if the cell is even or not?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You have to check the modulus to know whether it's even or odd. It's the simplest way. But I'd be wary of that divmod algorithm you posted. It should work when checking modulo 2 but if I remember correctly don't try to divide by 1 using it.

On a PC you could just AND the number with 1 (assuming it's an integer). But brainfuck doesn't have an AND operator, so you're going to have to go the long way round. You know the computer stores numbers in binary, but that's none of brainfuck's concern. It doesn't give you an array of binary values to manipulate. It gives you an array of numbers which you can only increment, decrement or compare to 0.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**