## Balanced Ternary Arithmetic

### April 14, 2015

We studied mixed-radix arithmetic in a previous exercise. In today’s exercise we look at a different kind of non-standard positional notation: balanced ternary, which is a base-3 number system that uses -1, 0 and 1 as its “trits” rather than 0, 1 and 2. For instance, the number -47 is written as (-1 1 1 -1 1) in balanced ternary, which is equivalent to -3^{4} + 3^{3} + 3^{2} – 3^{1} + 3^{0}. No separate sign is needed when using balanced notation; the sign of the leading trit is the sign of the whole number.

Arithmetic on balanced ternary numbers is done using the grade-school algorithms. Addition is done right-to-left with a carry; it is easy and fun to work out the plus-table. Subtraction is done by adding the negative, which can be computed by changing the sign of every trit. Multiplication works trit-by-trit through the multiplier, shifting at each trit.

Your task is to write functions that perform arithmetic on balanced ternary integers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

In Python.

We can do this in a similar way to the previous problem, here most of the work is done by the “adjust” function which puts a single digit into the correct range and adjusts the carry accordingly. I’ve added a separate “normalize” function, and we can simplify addition assuming the inputs are normalized:

That mult function is wrong – it throws away the final carry from each addition. Here’s a better version (and a better test program):

See this web site for a library of C (works in C++ too) code allowing use of binary-coded ternary data representations, coding each ternary trit as two consecutive binary bits.

— http://www.cs.uiowa.edu/~jones/ternary/libtern.shtml

This does a ternary add in about 10 times the time it takes for a corresponding integer add, so it’s way more efficient than the digit serial code shown above. There’s support there for both balanced ternary (trit values -1 0 +1) and unsigned ternary (trit values 0 1 2).