Bill Allombert on Sun, 22 Oct 2023 22:12:32 +0200


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

Re: sumdigits(n,B) doesn't refuse B < -1


On Fri, Oct 20, 2023 at 07:12:42AM +0200, Martin Becker wrote:
> 
> Hello Pari Devs,
> 
> On Tue, Oct 17, 2023 at 09:29:59AM +0200, Ruud H.G. van Tol wrote:
> > ? sumdigits(12345,-4)
> > % 5
> >
> > Expected:
> >
> >  *** at top-level: sumdigits(12345,-4)
> >  *** ^------------------
> >  *** sumdigits: domain error in digits: B < 2
> >  *** Break loop: type 'break' to go back to GP prompt
> > break>
> 
> While Ruud is certainly right that digits() und sumdigits()
> should behave consistently, negative bases actually do make
> sense, cf. Donald E. Knuth, The art of computer programming,
> vol. 2, Seminumerical algorithms, chapter 4.1, Positional
> number systems, where he discusses, among other things,
> negative bases as well as negative digits.
> 
> In base -4, 12345 would be represented as [3, 0, 1, 3, 0, 2, 1],
> as 12345 == (((((3*-4 + 0)*-4 + 1)*-4 + 3)*-4 + 0)*-4 + 2)*-4 + 1,
> and the sum of these digits is 10.

> I would like Pari to implement some of these numeral systems,
> like base -2 or balanced ternary (using base 3 with digits -1,
> 0, and 1). The former could be an extension of the input range
> of digits(), the latter a function similar to digits() named
> balanceddigits(), say.

As I say, there are too many variations.

The goal of digits() is to provide an asymptotically fast algorithm.
Once you have the result for set of digits, you can recoved the result
for other sets of digits in linear time, as negdigits shows.

Please see baldigits in the following script
https://pari.math.u-bordeaux.fr/Scripts/negdigits.gp
to handle balanced digits by the same method.

Cheers,
Bill.