Martin Becker on Fri, 20 Oct 2023 07:12:52 +0200


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

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


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.

These would be rather small additions, whereas supporting bases
like I-1 or sqrt(2) would perhaps not justify the effort.

-Martin