/* Copyright (C) 2023 The PARI group PARI/GP is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY WHATSOEVER. Check the License for details. You should have received a copy of it, along with the package; see the file 'COPYING'. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ addhelp("negdigits","negdigits(n,b): write n in base b<0 with digits 0..|b|-1") 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); } addhelp("baldigits","baldigits(n,b): write n in odd base b>0 with digits between -b/2 and b/2"); baldigits(n,B)= { my(b = B\2); my(V=digits(abs(n),B)); my(carry=0); if(n<0,V=-V); for(i=0,#V-1, my(u=V[#V-i]+carry); if (u<-b,u+=B;carry=-1, u>b,u-=B;carry=1, carry=0); V[#V-i]=u); if (carry, concat(carry,V),V); } test_negdigits()= { for(n=-10000,10000,if(fromdigits(negdigits(n,-7),-7)!=n,error(n))); for(n=-10000,10000,if(fromdigits(baldigits(n,7),7)!=n,error(n))); }