| Bill Allombert on Sun, 15 Oct 2023 13:36:09 +0200 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
| Re: digits(n,-4) |
On Sun, Oct 15, 2023 at 12:46:48PM +0200, Ruud H.G. van Tol wrote: > > On 2023-10-14 20:34, Bill Allombert wrote: > > On Sat, Oct 14, 2023 at 07:24:35PM +0200, Ruud H.G. van Tol wrote: > > > ? fromdigits( [1,3,0], -4 ) > > > % 4 > > Note that we do need to know that the set of digits is here. > > > > > ? my(n=4, v=[]); while( n=divrem(n,-4), v=concat(n[2],v); n=n[1] ); v > > > % [1, 3, 0] > > > > > > Is there a better way to do this? > > I would start with use digits(n,16) and split the digits. > > Thanks, am still chewing on that. I offer the following which should handle all cases and has the benefit of being asymptotically fast. ? negdigits(-41,-4) %1 = [1,2,3,3] ? negdigits(41,-4) %2 = [3,2,1] Cheers, Bill.
negdigits(n,b)=
{
my(B=abs(b));
my(V=digits(abs(n),B));
if (b > 0, return(V));
my(carry=0);
if(n<0,V=-V);
for(i=0,#V-1,
my(u=V[#V-i]*(-1)^i+carry);
if (u<0,u+=B;carry=1,
u>=B,u-=B;carry=-1,
carry=0);
V[#V-i]=u);
if (carry>0, concat(carry,V),carry<0,concat([1,carry+B],V),V);
}