Ruud H.G. van Tol on Wed, 29 Dec 2021 22:59:58 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: factor(x+1)



On 2021-12-29 20:25, Ruud H.G. van Tol wrote:

A 2,3 specific variant:
[...]
My next step could be to use a t_INT when there is a zero.

I have no specific use for this yet,
it is still mainly a personal code exercise.

While making this variant,
I hit some interesting bugs,
like decode(encode(13)) returning 53.
(under Collatz, 3*53+1 -> 5, 3*13+1 -> 5,
because 53=8i+5, so can be replaced by 2i+1, repeatedly)
(Remember Bob Ross's Happy Accidents?)

The current encoding has a redundant side.
For example 26, can now be encoded as terse as
[0, -3] \\ 3^3-1
but also as
[1,[1,[3,0]]]  \\ 2*(2*(2^3-1)-1)
which I currently like about it,
but I feel that it still can be improved.

-- Ruud


This time I left in some handy DEBUG code.

tofp23(x0, m= 0, DL= 0)= {
  if( x0 < 1,return([]) );

  if(DL,print("-to-1.x0=",x0," m=",m));
  my
  ( x=  x0 + m
  , v2= valuation(x,2)
  , v3= valuation(x,3)
  );
  if(DL,print("-to-1.x=",x," v2=",v2," v3=",v3));

  x/= 2^v2;
  x/= 3^v3;
  my
  ( v= if
       ( x == 1
       , if
         ( m
         , [v2,v3]
         , [if(v2,if(v3,[v2,v3],v2),-v3)]
         );
       , [ (if(v2,if(v3,[v2,v3],v2),-v3))
         , tofp23(x,1,DL)
         ];
       );
  );
  if(DL,print("-to-1.v=",v));
  v;
}

fromfp23(v, DL= 0)= {
  if(!#v, return(0));

  v= Vecrev(v);
  if(DL,print("-fr-1.v=",v));

  my(n= 1);
  for
  ( i=1, #v
  , my( w= v[i] );
    if(DL,print("-fr-2.w=",w));

    if
    ( type(w) != "t_VEC"
    , w= if(w<0,[0,-w],[w,0]);
    );
    if(DL,print("-fr-3.w=",w));

    my( f= if
           ( (type(w[1]) == "t_VEC")
           ||(type(w[2]) == "t_VEC")
           , fromfp23(w, DL);
           , (2^w[1]*3^w[2]);
           );
    );
    if(DL,print("-fr-8.f=",f));

    n*= if( i < #v, f-1, f);
    if(DL,print("-fr-9.n=",n));
  )
  ;n
}

{ my(DL= 0);
  for(i=1, 19
  , my( v= tofp23(i,0,DL) );
    print(i,": ", v, " -> ", fromfp23(v,0))
  );
}