Max Alekseyev on Thu, 18 Oct 2012 15:38:04 +0200


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

Re: reverse of digits()


JFI, In base 10, some digits-related functions can be implemented as
one-liners, e.g.:

\\ getting vector of digits of n:
eval(Vec(Str(n)))

\\ getting number from its vector of digits v:
eval(concat(apply(x->Str(x),v)))

\\ getting number composed of digits of n in reverse order:
eval(concat(Vecrev(Str(n))))

Regards,
Max

On Wed, Oct 17, 2012 at 9:01 PM, Mathieu Carbou
<mathieu.carbou@gmail.com> wrote:
> Hello,
>
> I've seen the new digits() and sumdigits() functions. I was wondering if
> there was also the reverse function of digits (i.e. vectonum([1,2,3,4,5],
> 10) == 12345) plus these functions which could be useful ;-)
>
> Thank you !
>
> /*
>     Digit decomposition of n in base b by ascending order of b exponents.
> I.e. digits(12345) == [1,2,3,4,5]
> */
> vectonum(v, b=10) =
> {
>     my(n=0);
>     for(i=1,#v, n+=v[i]*b^(#v-i));
>     return(n);
> }
>
> /*
>     Number of digits of n in base b
> */
> ndigits(n, b=10) =
> {
>     my(c=0);
>     if(n==0, return(1));
>     while(n, n=n\b; c++);
>     return(c);
> }
>
> /*
>     Representation of n in factoradic base b.
>     The number n is taken modulo b!
> */
> factoradic(n, b=10) =
> {
>     my(v=vector(b), qr=[0,n%(b!)]);
>     for(i=1, b, qr=divrem(qr[2], (b-i)!); v[i]=qr[1]);
>     return(v);
> }
>
>
> --
>
> Mathieu Carbou
> Cell: 514-660-4287