Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, i.e. X mod 2 is the rightmost bit of X, I think that divmod might be overkill in terms of complexity of calculation.

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

like image 976
Jay Bosamiya Avatar asked Dec 24 '22 16:12

Jay Bosamiya


2 Answers

You need an algorithm that keeps only parity, you could do it like that :

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

To test n without losing its value, you need to copy it : copy from A to B and C then move C to A. You could test B and keep n into A. Here is the brainfuck 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-form:

[->+<]>[-<+>[->+>+<<]>>[-<<+>>]<[<-<->>[-]]<]<
like image 135
alexscott Avatar answered Feb 20 '23 05:02

alexscott


N odd or even:

>,             load m1 with N

[-[->]<]+      set m0 = 1 if odd
               set m1 = 1 if even
like image 21
6502asm Avatar answered Feb 20 '23 06:02

6502asm