91 lines
2.4 KiB
Text
91 lines
2.4 KiB
Text
function bt2dec(string bt)
|
|
integer res = 0
|
|
for i=1 to length(bt) do
|
|
res = 3*res+(bt[i]='+')-(bt[i]='-')
|
|
end for
|
|
return res
|
|
end function
|
|
|
|
function negate(string bt)
|
|
for i=1 to length(bt) do
|
|
if bt[i]!='0' then
|
|
bt[i] = '+'+'-'-bt[i]
|
|
end if
|
|
end for
|
|
return bt
|
|
end function
|
|
|
|
function dec2bt(integer n)
|
|
string res = "0"
|
|
integer neg, r
|
|
if n!=0 then
|
|
neg = n<0
|
|
if neg then n = -n end if
|
|
res = ""
|
|
while n!=0 do
|
|
r = mod(n,3)
|
|
res = "0+-"[r+1]&res
|
|
n = floor((n+(r=2))/3)
|
|
end while
|
|
if neg then res = negate(res) end if
|
|
end if
|
|
return res
|
|
end function
|
|
|
|
-- res,carry for a+b+carry lookup tables (not the fastest way to do it, I'm sure):
|
|
constant {tadd,addres} = columnize({{"---","0-"},{"--0","+-"},{"--+","-0"},
|
|
{"-0-","+-"},{"-00","-0"},{"-0+","00"},
|
|
{"-+-","-0"},{"-+0","00"},{"-++","+0"},
|
|
{"0--","+-"},{"0-0","-0"},{"0-+","00"},
|
|
{"00-","-0"},{"000","00"},{"00+","+0"},
|
|
{"0+-","00"},{"0+0","+0"},{"0++","-+"},
|
|
{"+--","-0"},{"+-0","00"},{"+-+","+0"},
|
|
{"+0-","00"},{"+00","+0"},{"+0+","-+"},
|
|
{"++-","+0"},{"++0","-+"},{"+++","0+"}})
|
|
|
|
|
|
function bt_add(string a, string b)
|
|
integer pad = length(a)-length(b)
|
|
integer carry = '0'
|
|
if pad!=0 then
|
|
if pad<0 then
|
|
a = repeat('0',-pad)&a
|
|
else
|
|
b = repeat('0',pad)&b
|
|
end if
|
|
end if
|
|
for i=length(a) to 1 by -1 do
|
|
{a[i],carry} = addres[find(a[i]&b[i]&carry,tadd)]
|
|
end for
|
|
if carry!='0' then
|
|
a = carry&a
|
|
else
|
|
while length(a)>1 and a[1]='0' do
|
|
a = a[2..$]
|
|
end while
|
|
end if
|
|
return a
|
|
end function
|
|
|
|
function bt_mul(string a, string b)
|
|
string pos = a, neg = negate(a), res = "0"
|
|
integer ch
|
|
for i=length(b) to 1 by -1 do
|
|
ch = b[i]
|
|
if ch='+' then
|
|
res = bt_add(res,pos)
|
|
elsif ch='-' then
|
|
res = bt_add(res,neg)
|
|
end if
|
|
pos = pos&'0'
|
|
neg = neg&'0'
|
|
end for
|
|
return res
|
|
end function
|
|
|
|
string a = "+-0++0+", b = dec2bt(-436), c = "+-++-"
|
|
|
|
?{bt2dec(a),bt2dec(b),bt2dec(c)}
|
|
|
|
string res = bt_mul(a,bt_add(b,negate(c)))
|
|
?{res,bt2dec(res)}
|