Find an algorithm for writing any positive integer in negabinary, i.e., as a sum of powers of 2.
For example,
7 = 11011 = (2)^4 + (2)^3 + (2)^1 + (2)^0
19 = 10111 = (2)^4 + (2)^2 + (2)^1 + (2)^0
As with any base arithmetic, we need to take remainders mod the base, then divide the preceding value (in the first instance, the number to be represented) by the base, and continue from there.
In ordinary binary, for 6 we'd just do this:
6/2 = 3 remainder 0: so far it's 0
3/2 = 1 remainder 1: so far it's 10 (as the new remainder is placed to the left of the old ones)
1/2 = 0 remainder 1: it's now 110
In base 2:
6/2 = 3 remainder 0: so far it's 0
3/2 = 1 remainder 1 or 2 remainder 1 (we need to use a positive remainder as negative signs can't be used within a notation): so far it's 10
2 / 2 = 1 remainder 0: so far it's 010
1 / 2 = 0 remainder 1 or 1 remainder 1: so far it's 1010
1/2 = 0 remainder 1: it's now 11010
The only difference that a negative base makes is that if the remainder appears to be negative (which happens only with a negative dividend), we must adjust the quotient up by 1 (it's up, since the divisor is negative) and the remainder up by the absolute value of the base. This is accomplished by the line labeled 1 in the program below
b = 2
DO
INPUT n
s$ = "": pv = 1
WHILE n <> 0
q = n \ b
r = n MOD b
1 IF r < 0 THEN r = r  b: q = q  SGN(b)
PRINT q, r, pv
s$ = LTRIM$(STR$(r)) + s$
n = q
pv = pv * b
WEND
PRINT s$
LOOP
In the case of 6 it produces (my headings added):
? 6
quotient remainder place value
3 0 1
2 1 2
1 0 4
1 1 8
0 1 16
final representation:
11010
It is of interest that this will work even with negative numbers, as the adjustment step can act upon that as well, where the number itself is the first number to be divided and is thus subject to negative remainders before adjustment:
? 6
3 0 1
1 1 2
1 1 4
0 1 8
1110
so 6 is 1110 giving 8 * 1 + 4 * 1 + 2 * 1 + 0 = 6.
Try 150 and 150:
? 150
75 0 1
38 1 2
19 0 4
10 1 8
5 0 16
3 1 32
1 1 64
1 1 128
0 1 256
111101010
? 150
75 0 1
37 1 2
19 1 4
9 1 8
5 1 16
2 1 32
1 0 64
0 1 128
10111110

Posted by Charlie
on 20130815 02:37:51 