Derive an algorithm for writing any positive base ten integer in Balanced Ternary (base 3) number system.
As an extra challenge, extend this to writing base ten positive rational and irrational numbers in Balanced Ternary number system.
digs='a01234';
for n=0:15
b3=dec2bse(n,3);
fprintf('%6d %3s ',n,b3)
bb3='';
carry=0;
while ~isempty(b3) || carry>0
if isempty(b3)
b3='0';
end
c=b3(end);
ix=strfind(digs,c)+carry;
if ix>3
ix=ix-3 ;
c=digs(ix);
carry=1;
else
carry=0;
if ix~=0
c=digs(ix);
end
end
b3=b3(1:end-1);
bb3=[ c bb3];
end
fprintf(' %s\n',bb3)
end
function inbase=dec2bse(d,b,minlen)
outval=''; s='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
d2=d;
while d2>0
r=mod(d2,b);
outval=[s(r+1) outval];
d2=(d2-r)/b;
end
if ~exist('minlen','var')
minlen=1;
end
if length(outval)<minlen
outval=[repmat('0',1,minlen-length(outval)) outval];
end
inbase=outval;
end
uses lower case a to represent the digit -1.
The algorithm works first by converting to ternary by the usual remainder and quotient-becoming-dividend method. Then the result is analyzed from right to left, with any 2's being converted to -1 and a carry of 1 is made into the next digit to the left. Any 3's resulting from a 2 and a carry are just converted to zeros. In examining the code, note that the digit list starts with a value of zero in position 1, as Matlab is 1-based for subscripts.
decimal ternary balanced ternary
0 0 0
1 1 1
2 2 1a
3 10 10
4 11 11
5 12 1aa
6 20 1a0
7 21 1a1
8 22 10a
9 100 100
10 101 101
11 102 11a
12 110 110
13 111 111
14 112 1aaa
15 120 1aa0
|
Posted by Charlie
on 2022-11-04 11:31:44 |