Figuring out if a number in a cell is even or odd

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

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

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

      

I know there is a divmod algorithm defined like this:

If you don't need to store n, use this option:

# >n d
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
# >0 d-n%d n%d n/d

      

However, since X % 2 == X & 1

, i.e. X mod 2 is the rightmost bit of X, I think divmod might be overflowing in terms of computation complexity.

Is there a better algorithm / method for determining if a cell is even or not?

+3


source to share


4 answers


You need to check the module to find out if it is even or odd. This is the easiest way. But I would be wary of this divmod algorithm you posted. It should work when checked modulo 2, but if I remember correctly, don't try to divide by 1 using it.



On a PC, you can just AND a number with 1 (assuming it's an integer). But brain bias doesn't have an AND operator, so you'll have a long way to go. You know the computer stores numbers in binary, but that's not a brain problem. It doesn't give you an array of binary values ​​to control. It gives you an array of numbers that you can only increment, decrement, or compare with 0.

0


source


You need an algorithm that only preserves parity, you can do it like this:

result=0
while(n > 0) {
  result++;
  n--;
  if(n > 0) {
    result--;
    n--;
  }
}

      

To check n without losing its value, you need to copy it: copy from A to B and C, then move C to A. You can check B and store n in A. Here is the brain code:



[->+<] # move @0 to @1
> # goto @1
[-<+ # if @1 then decrements @1 and increments @0
 > # goto @1
 [->+>+<<] # if @1 then move @1 to @2 and @3
 >> # goto @3
 [-<<+>>] # if @3 then move @3 to @1
 < # goto @2
 [<-<->>[-]] # if @2 then decrements @0, decrements @1 and sets 0 into @2
 < # go to @1
] # continue loop if @1 is not null
< # goto @0

      

light shape:

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

      

+5


source


N is odd or even:

>,             load m1 with N

[-[->]<]+      set m0 = 1 if odd
               set m1 = 1 if even

      

+2


source


Here's a version that resolves P completely:

Is it odd or even?

>,              ~load m1 with N (not counted for golf scoring)
>>+>+<<<        ~set 'trail of breadcrumbs' so we can figure out 
                   where P is
[-[->]<]+       ~if N is odd set m0 = 1
>>>[>]          ~figure out where P is
<[-<]<[-]<      ~go back to m1 and zero out if N is even

      

Pointer P ends with m0 odd: m0 = 1 even: m0 = 0

+2


source







All Articles