Anonymous user
Balanced ternary: Difference between revisions
m
→{{header|REXX}}: added/changed comments and whitespace, used a template for the OUTPUTs, optimized a function.
(Added Julia language) |
m (→{{header|REXX}}: added/changed comments and whitespace, used a template for the OUTPUTs, optimized a function.) |
||
Line 4,051:
=={{header|REXX}}==
The REXX program could be optimized by using (procedure) with '''expose''' and having the <big>'''$.'''</big> and <big>'''@.'''</big> variables set only once.
<lang rexx>/*REXX
numeric digits 10000 /*be able to handle gihugic numbers. */
Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/
Bo = '-436' ; Bbt = d2bt(Bo);
Co = '+-++-' ; Cbt = Co ;
call btShow '[a]', Abt
call btShow '[b]', Bbt
call btShow '[c]', Cbt
say; $bt = btMul(Abt, btSub(Bbt, Cbt) )
call btShow '[a*(b-c)]', $bt
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
d2bt: procedure; parse arg x 1; p=0; $.='-'; $.1='+'; $.0=0; #=
x=x / 1
do until x==0;
if _==
end /*until*/;
/*──────────────────────────────────────────────────────────────────────────────────────*/
bt2d: procedure; parse arg x; r=reverse(x); #=0; $.=-1; $.0=0; _='+'; $._=1▼
return #▼
/*──────────────────────────────────────────────────────────────────────────────────────*/
▲bt2d: procedure; parse arg x; r=reverse(x); #=0; $.=-1; $.0=0; _='+'; $._=1
▲ do j=1 for length(x); _=substr(r,j,1); #=#+$._*3**(j-1); end
▲btAdd: procedure; parse arg x,y; rx=reverse(x); ry=reverse(y); carry=0
y_=substr(ry, j, 1); yn=@.y_
▲ $.='-'; $.0=0; $.1='+'
if carry\==0 then #=$.carry || #;
/*──────────────────────────────────────────────────────────────────────────────────────*/
▲ #=$.s || #
btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return
if y1=='-' then do; y=btNeg(y); S=-S; end /* " " " */
▲if x1=='-' then do; x=btNeg(x); S=-S; end /*positate.*/
y=btSub(y, '+') /*subtract 1 from Y.*/
if S==-1 then P=btNeg(P); return P /*adjust the product sign; return.
/*──────────────────────────────────────────────────────────────────────────────────────*/
▲ y=btSub(y,'+') /*subtract 1 from Y.*/
btNeg: return translate(arg(1), '-+', "+-") /*negate bal_ternary
btShow: say center(arg(1),9) right(arg(2),20) @@ right(bt2d(arg(2)),9) @; return</lang>▼
▲btNorm: _=strip(arg(1),'L',0); if _=='' then _=0; return _ /*normalize a #*/
▲btShow: say center(arg(1),9) right(arg(2),20) @@ right(bt2d(arg(2)),9) @; return</lang>
▲'''output''' when using the default inputs:
<pre>
[a] +-0++0+ balanced ternary = 523 (decimal)
|