Function Repository Resource:

BalancedTernary

Source Notebook

Convert integers to and from balanced ternary

Contributed by: Ed Pegg Jr

ResourceFunction["BalancedTernary"][n]

toggles the n between integer and balanced ternary format.

Details

ResourceFunction["BalancedTernary"] toggles between ordinary integer format and a format specific to the balanced ternary representation of an integer.
In balanced ternary, represents 56.
+1×34-1×33+0×32+1×31-1×30 = 56.
{1,-1,0,1,-1}.3{4,3,2,1,0} = 56.
{1,-1,0,1,-1} is rewritten as for balanced ternary.

Examples

Basic Examples (2) 

Convert some integers to balanced ternary format:

In[1]:=
ResourceFunction["BalancedTernary"] /@ Range[-9, 9]
Out[1]=

Convert the balanced ternary numbers back into integers:

In[2]:=
ResourceFunction["BalancedTernary"] /@ %
Out[2]=

Scope (2) 

Large numbers can be converted into balanced ternary:

In[3]:=
Column[Table[ResourceFunction["BalancedTernary"][10^n], {n, 1, 12}]]
Out[3]=

Create a random 20-digit balanced ternary number:

In[4]:=
Row[RandomChoice[Normal[ResourceFunction["BalancedTernary"][6]], 20]]
Out[4]=

Convert to an integer:

In[5]:=
ResourceFunction["BalancedTernary"][%]
Out[5]=

Properties and Relations (1) 

Balanced ternary numbers are expressed in Row form:

In[6]:=
Head[ResourceFunction["BalancedTernary"][6]]
Out[6]=

Neat Examples (1) 

Using weights of size 1, 3, 9 and 27 and a 2-sided balance, measure weights 1 to 20:

In[7]:=
Grid[Transpose[
  Table[With[{l = PadLeft[Normal[ResourceFunction["BalancedTernary"][k]] /. 
\!\(\*UnderscriptBox[\(1\), \(_\)]\) -> -1, 4]},
    Append[l (3^Range[3, 0, -1]) /. 0 -> "" , k]], {k, 1, 20}]], Frame -> All, Dividers -> {Automatic, {-2 -> {Red, Thick}}}]
Out[7]=

Version History

  • 1.0.0 – 01 March 2021

License Information