Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums;

the same notation can be confusingly seen being used for the two different definitions.

Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:

     !n`   
     !n  
     n¡  


(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)



This Rosetta Code task will be using this formula   (factorial sums)   for   left factorial:


   



!
n
=

∑

k
=
0


n
−
1


k
!


{\displaystyle !n=\sum _{k=0}^{n-1}k!}




 where


   



!
0
=
0


{\displaystyle !0=0}






Task
Display the left factorials for:

   zero through ten     (inclusive)
   20   through   110   (inclusive)   by tens


Display the length (in decimal digits) of the left factorials for:

   1,000   through   10,000   (inclusive), by thousands.


Also see

   The OEIS entry: A003422 left factorials
   The MathWorld entry: left factorial
   The MathWorld entry: factorial sums
   The MathWorld entry: subfactorial


Related task

   permutations/derangements (subfactorials)


with javascript_semantics 
include mpfr.e
 
sequence lf_list
 
procedure init(integer n)
    mpz f = mpz_init(1)
    lf_list = repeat(f,n+1)
    for i=1 to n do
        f = mpz_init_set(f)
        mpz_mul_si(f,f,i)
        lf_list[i+1] = f
    end for
end procedure
 
function lf(integer n, bool len=false)
-- Returns left factorial of n, or it's length, as a string
    mpz sumf = mpz_init(0)
    for k=1 to n do mpz_add(sumf,sumf,lf_list[k]) end for
    return iff(len?sprintf("%d",mpz_sizeinbase(sumf,10))
                  :shorten(mpz_get_str(sumf)))
end function
 
-- Main procedure
atom t0 = time()
init(10000)
for i=0 to 10 do printf(1,"!%d = %s\n",{i,lf(i)}) end for
for i=20 to 110 by 10 do printf(1,"!%d = %s\n",{i,lf(i)}) end for
for i=1000 to 10000 by 1000 do printf(1,"!%d contains %s digits\n",{i,lf(i,true)}) end for
printf(1,"complete (%3.2fs)\n",{time()-t0})
