How to convert from unbalanced to balanced triple?

My goal is to convert decimal to balanced triple. Converting from decimal to unbalanced triple simply requires dividing by 3 and tracking the remainders. Once I have an unbalanced three-dimensional representation of a number, I cannot figure out how to “balance” it.

For example: 15 in decimal - 120 in an unbalanced triple and + - 0 in a balanced triple. How do I go from 120 to + - 0? I can't figure out how to deal with 2s in an unbalanced triple view.

Thank!

+5
source share
3 answers

, 2 + - 2 = 3 - 1. , , 0, 1 2, 2 -1 1 . (, 0 , , 2.) , , 3s 0, 1 , . , 2s ( 3s).

+5

, 2 x, -1 x+1.

, , .

String output="";
while (n>0) {
   rem = n%3;
   n = n/3;
   if (rem == 2) {
       rem = -1;
       n++;
   }
   output = (rem==0?'0':(rem==1)?'+':'-') + output;
}

.

+2

Since I missed this on the Internet, here is my own implementation in Pari / GP -

{balanced_ternary(x,maxdigits=20,chars=["y","0","1"])=my(res,st,dez,dig);
      dez=floor(log(abs(2*x))/log(3)); 
      res=x/3^dez;
      st=""; 
      for(k=0,maxdigits,
               if(k==dez+1,st=Str(st,"."));
               dig = if(res>1/2 
                       ,res--;chars[2+1]
                       ,if(res<-1/2
                              ,res++;chars[2-1]
                              ,chars[2+0]
                 )); 
               st=Str(st,dig);res*=3
           );
       return(st);}

Then

balancedternary (1)    \\ %1002 = "1.00000000000000000000"
balancedternary (-1)   \\ %1003 = "y.00000000000000000000"
balancedternary (1.2)  \\ %1004 = "1.1yy11yy11yy11yy11yy1"
balancedternary (-1.2) \\ %1005 = "y.y11yy11yy11yy11yy11y"

balancedternary (27-3) \\ %1006 = "10y0.00000000000000000"
balancedternary (400)  \\ %1007 = "1yy0y11.00000000000000"
balancedternary (sqrt(3))   \\ %1008 = "1y.y1yy10y0000yy1100y0"
balancedternary (sqrt(3)/3) \\ %1009 = "1.yy1yy10y0000yy1100y0"

Just q & d, not all "special cases" are marked / encoded.

0
source

All Articles