Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from unbalanced to balanced ternary?

My goal is to convert a decimal number into balanced ternary. Converting from decimal to unbalanced ternary simply requires division by 3 and keeping track of remainders. Once I have the unbalanced ternary representation of the number I can't seem to figure out how to "balance" it.

For example: 15 in decimal is 120 in unbalanced ternary and +--0 in balanced ternary. How do I go from 120 to +--0? I can't figure out how to deal with the 2s in the unbalanced ternary representation.

Thank you!

like image 242
corecase Avatar asked Oct 19 '14 23:10

corecase


1 Answers

Note that 2 in ternary is +- in balanced ternary, or in decimal 2 = 3 - 1. So if you start with an array filled with 0s, 1s, and 2s, just replace every 2 with a -1 and add 1 to the number to its left. (Make sure you have an extra 0 at the beginning of the number, at least if it starts with a 2.) Depending on how you do the replacement you may also need to replace 3s with 0s, adding 1 to the left as usual. Then repeat the process until there are no more 2s (or 3s).

like image 160
Charles Avatar answered Sep 17 '22 18:09

Charles