Left factorials: Difference between revisions

Content added Content deleted
m (→‎{{header|R}}: Syntax highlighting.)
m (syntax highlighting fixup automation)
Line 49: Line 49:
{{trans|D}}
{{trans|D}}


<lang 11l>F left_fact(n)
<syntaxhighlight lang="11l">F left_fact(n)
BigInt result = 0
BigInt result = 0
BigInt factorial = 1
BigInt factorial = 1
Line 63: Line 63:
print(left_fact(i))
print(left_fact(i))
print("\nDigits in 1,000 through 10,000 by thousands:")
print("\nDigits in 1,000 through 10,000 by thousands:")
print((1000..10000).step(1000).map(i -> String(left_fact(i)).len))</lang>
print((1000..10000).step(1000).map(i -> String(left_fact(i)).len))</syntaxhighlight>


{{out}}
{{out}}
Line 89: Line 89:
Uses the Algol 68G LONG LONG INT type which has programmer definable precision.
Uses the Algol 68G LONG LONG INT type which has programmer definable precision.
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<lang algol68># set the precision of LONG LONG INT - large enough for !n up to ! 10 000 #
<syntaxhighlight lang="algol68"># set the precision of LONG LONG INT - large enough for !n up to ! 10 000 #
PR precision 36000 PR
PR precision 36000 PR
# stores left factorials in an array #
# stores left factorials in an array #
Line 156: Line 156:
OD
OD
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 197: Line 197:
=={{header|AWK}}==
=={{header|AWK}}==
Old posix AWK doesn't support computing with large numbers. However modern gawk can use GMP if the flag -M is used.
Old posix AWK doesn't support computing with large numbers. However modern gawk can use GMP if the flag -M is used.
<syntaxhighlight lang="awk">
<lang AWK>
#!/usr/bin/gawk -Mf
#!/usr/bin/gawk -Mf
function left_factorial(num) {
function left_factorial(num) {
Line 221: Line 221:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 260: Line 260:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Use the 'Mapm' library.
Use the 'Mapm' library.
<lang bbcbasic> INSTALL @lib$+"BB4WMAPMLIB" : PROCMAPM_Init : MAPM_Dec%=200
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"BB4WMAPMLIB" : PROCMAPM_Init : MAPM_Dec%=200


Result$="0" : A$="1"
Result$="0" : A$="1"
Line 270: Line 270:
IF I% > 999 IF I% MOD 1000 = 0 PRINT "!";I% " has " LENFNMAPM_FormatDec(Result$,0) " digits"
IF I% > 999 IF I% MOD 1000 = 0 PRINT "!";I% " has " LENFNMAPM_FormatDec(Result$,0) " digits"
NEXT
NEXT
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 307: Line 307:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
{{trans|D}}
{{trans|D}}
<lang bracmat>( ( leftFact
<syntaxhighlight lang="bracmat">( ( leftFact
= result factorial i
= result factorial i
. 0:?result
. 0:?result
Line 343: Line 343:
. (=L.@(!arg:? [?L)&out$!L)
. (=L.@(!arg:? [?L)&out$!L)
)
)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>First 11 left factorials:
<pre>First 11 left factorials:
Line 384: Line 384:
=={{header|C}}==
=={{header|C}}==
{{libheader|GMP}}
{{libheader|GMP}}
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 435: Line 435:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 472: Line 472:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Numerics;
using System.Numerics;
Line 525: Line 525:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 563: Line 563:
Faster Implementation
Faster Implementation


<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Numerics;
using System.Numerics;
Line 614: Line 614:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang="cpp">
<lang CPP>
#include <vector>
#include <vector>
#include <string>
#include <string>
Line 745: Line 745:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 783: Line 783:
===Faster alternative===
===Faster alternative===
{{libheader|GMP}}
{{libheader|GMP}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <gmpxx.h>
#include <gmpxx.h>


Line 820: Line 820:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 861: Line 861:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(ns left-factorial
<syntaxhighlight lang="lisp">(ns left-factorial
(:gen-class))
(:gen-class))


Line 880: Line 880:
(doseq [n (range 1000 10001 1000)]
(doseq [n (range 1000 10001 1000)]
(println (format "!%-5d has %5d digits" n (count (str (biginteger (left-factorial n)))))))
(println (format "!%-5d has %5d digits" n (count (str (biginteger (left-factorial n)))))))
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 917: Line 917:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(defun fact (n)
(defun fact (n)
(reduce #'* (loop for i from 1 to n collect i)))
(reduce #'* (loop for i from 1 to n collect i)))
Line 930: Line 930:
(format t "1000 -> 10000 by 1000~&")
(format t "1000 -> 10000 by 1000~&")
(format t "~{~a digits~&~}" (loop for i from 1000 upto 10000 by 1000 collect (length (format nil "~a" (left-fac i)))))
(format t "~{~a digits~&~}" (loop for i from 1000 upto 10000 by 1000 collect (length (format nil "~a" (left-fac i)))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 960: Line 960:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.bigint, std.range, std.algorithm, std.conv;
<syntaxhighlight lang="d">import std.stdio, std.bigint, std.range, std.algorithm, std.conv;


BigInt leftFact(in uint n) pure nothrow /*@safe*/ {
BigInt leftFact(in uint n) pure nothrow /*@safe*/ {
Line 977: Line 977:
writefln("\nDigits in 1,000 through 10,000 by thousands:\n%s",
writefln("\nDigits in 1,000 through 10,000 by thousands:\n%s",
iota(1_000, 10_001, 1_000).map!(i => i.leftFact.text.length));
iota(1_000, 10_001, 1_000).map!(i => i.leftFact.text.length));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>First 11 left factorials:
<pre>First 11 left factorials:
Line 999: Line 999:
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
We use the 'bigint' library and memoization : (remember 'function).
We use the 'bigint' library and memoization : (remember 'function).
<lang lisp>
<syntaxhighlight lang="lisp">
(lib 'bigint)
(lib 'bigint)
(define (!n n)
(define (!n n)
Line 1,005: Line 1,005:
(+ (!n (1- n)) (factorial (1- n)))))
(+ (!n (1- n)) (factorial (1- n)))))
(remember '!n)
(remember '!n)
</syntaxhighlight>
</lang>
Output:
Output:
<lang lisp>
<syntaxhighlight lang="lisp">
(for ((n 11)) (printf "!n(%d) = %d" n (!n n)))
(for ((n 11)) (printf "!n(%d) = %d" n (!n n)))
(for ((n (in-range 20 120 10))) (printf "!n(%d) = %d" n (!n n)))
(for ((n (in-range 20 120 10))) (printf "!n(%d) = %d" n (!n n)))
Line 1,046: Line 1,046:
Digits of !n(9000) = 31678
Digits of !n(9000) = 31678
Digits of !n(10000) = 35656
Digits of !n(10000) = 35656
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule LeftFactorial do
<syntaxhighlight lang="elixir">defmodule LeftFactorial do
def calc(0), do: 0
def calc(0), do: 0
def calc(n) do
def calc(n) do
Line 1,068: Line 1,068:
digits = LeftFactorial.calc(i) |> to_char_list |> length
digits = LeftFactorial.calc(i) |> to_char_list |> length
IO.puts "!#{i} has #{digits} digits"
IO.puts "!#{i} has #{digits} digits"
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 1,107: Line 1,107:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
===The Functıon===
===The Functıon===
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Generate Sequence of Left Factorials: Nigel Galloway, March 5th., 2019.
// Generate Sequence of Left Factorials: Nigel Galloway, March 5th., 2019.
let LF=Seq.unfold(fun (Σ,n,g)->Some(Σ,(Σ+n,n*g,g+1I))) (0I,1I,1I)
let LF=Seq.unfold(fun (Σ,n,g)->Some(Σ,(Σ+n,n*g,g+1I))) (0I,1I,1I)
</syntaxhighlight>
</lang>
===The Tasks===
===The Tasks===
;Display LF 0..10
;Display LF 0..10
<lang fsharp>
<syntaxhighlight lang="fsharp">
LF |> Seq.take 11|>Seq.iter(printfn "%A")
LF |> Seq.take 11|>Seq.iter(printfn "%A")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,131: Line 1,131:
</pre>
</pre>
;Display LF 20..110 in steps of 10
;Display LF 20..110 in steps of 10
<lang fsharp>
<syntaxhighlight lang="fsharp">
LF |> Seq.skip 20 |> Seq.take 91 |> Seq.iteri(fun n g->if n%10=0 then printfn "%A" g)
LF |> Seq.skip 20 |> Seq.take 91 |> Seq.iteri(fun n g->if n%10=0 then printfn "%A" g)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,148: Line 1,148:
</pre>
</pre>
;Display the length (in decimal digits) of LF 1000 .. 10000 in steps of 1000
;Display the length (in decimal digits) of LF 1000 .. 10000 in steps of 1000
<lang fsharp>
<syntaxhighlight lang="fsharp">
LF |> Seq.skip 1000 |> Seq.take 9001 |> Seq.iteri(fun n g->if n%1000=0 then printfn "%d" (string g).Length)
LF |> Seq.skip 1000 |> Seq.take 9001 |> Seq.iteri(fun n g->if n%1000=0 then printfn "%d" (string g).Length)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,167: Line 1,167:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang>USING: formatting fry io kernel math math.factorials
<syntaxhighlight lang="text">USING: formatting fry io kernel math math.factorials
math.functions math.parser math.ranges sequences ;
math.functions math.parser math.ranges sequences ;
IN: rosetta-code.left-factorials
IN: rosetta-code.left-factorials
Line 1,193: Line 1,193:
: main ( -- ) part1 part2 part3 ;
: main ( -- ) part1 part2 part3 ;


MAIN: main</lang>
MAIN: main</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,235: Line 1,235:
{{works with|Gforth 0.7.3}}
{{works with|Gforth 0.7.3}}
This solution inspired by the Fortran one.
This solution inspired by the Fortran one.
<lang Forth>36000 CONSTANT #DIGITS \ Enough for !10000
<syntaxhighlight lang="forth">36000 CONSTANT #DIGITS \ Enough for !10000
CREATE S #DIGITS ALLOT S #DIGITS ERASE VARIABLE S#
CREATE S #DIGITS ALLOT S #DIGITS ERASE VARIABLE S#
CREATE F #DIGITS ALLOT F #DIGITS ERASE VARIABLE F#
CREATE F #DIGITS ALLOT F #DIGITS ERASE VARIABLE F#
Line 1,282: Line 1,282:
dup REPORT
dup REPORT
dup F F# @ rot B* F# !
dup F F# @ rot B* F# !
1+ REPEAT drop ;</lang>
1+ REPEAT drop ;</syntaxhighlight>
{{out}}
{{out}}
<pre>$ gforth left-factorials.fs -e 'GO bye'
<pre>$ gforth left-factorials.fs -e 'GO bye'
Line 1,324: Line 1,324:
Because this calculation won't get far, no attempt is made to save intermediate results (such as the factorial numbers) nor develop the results progressively even though they are to be produced in sequence. Each result is computed from the start, as per the specified formulae.
Because this calculation won't get far, no attempt is made to save intermediate results (such as the factorial numbers) nor develop the results progressively even though they are to be produced in sequence. Each result is computed from the start, as per the specified formulae.


For output, to have the exclamation mark precede the number without a gap, format sequence <code>"!",I0</code> will do, the <code>I0</code> format code being standardised in F90. However, this produces varying-length digit sequences, which will mean that the following output changes position likewise. Rather than use say <code>I20</code> for the result and have a wide gap, code <code>I0</code> will do, and to start each such number in the same place, the code <code>T6</code> will start it in column six, far enough along not to clash with the first number on the line, given that it will not be large. <lang Fortran> MODULE LAIROTCAF !Calculates "left factorials".
For output, to have the exclamation mark precede the number without a gap, format sequence <code>"!",I0</code> will do, the <code>I0</code> format code being standardised in F90. However, this produces varying-length digit sequences, which will mean that the following output changes position likewise. Rather than use say <code>I20</code> for the result and have a wide gap, code <code>I0</code> will do, and to start each such number in the same place, the code <code>T6</code> will start it in column six, far enough along not to clash with the first number on the line, given that it will not be large. <syntaxhighlight lang="fortran"> MODULE LAIROTCAF !Calculates "left factorials".
CONTAINS !The usual suspects.
CONTAINS !The usual suspects.
INTEGER*8 FUNCTION FACT(N) !Factorial, the ordinary.
INTEGER*8 FUNCTION FACT(N) !Factorial, the ordinary.
Line 1,361: Line 1,361:
WRITE (6,1) I,LFACT(I)
WRITE (6,1) I,LFACT(I)
END DO
END DO
END</lang>
END</syntaxhighlight>


Output:
Output:
Line 1,382: Line 1,382:
</pre>
</pre>


Obviously, one could proceed using the services of some collection of "bignum" routines, and then the code would merely depict their uses for this problem. Since the task is to produce consecutive values, all that need be done is to maintain a S value holding the accumulated sum, and a F value for the successive factorials to be added into S. The only difficulty is to arrange the proper phasing of the starting values so that the calculation will work. Since only one multiply and one addition is needed per step, explicit code might as well be used, as follows: <lang Fortran>Calculates "left factorials", in sequence, and shows some.
Obviously, one could proceed using the services of some collection of "bignum" routines, and then the code would merely depict their uses for this problem. Since the task is to produce consecutive values, all that need be done is to maintain a S value holding the accumulated sum, and a F value for the successive factorials to be added into S. The only difficulty is to arrange the proper phasing of the starting values so that the calculation will work. Since only one multiply and one addition is needed per step, explicit code might as well be used, as follows: <syntaxhighlight lang="fortran">Calculates "left factorials", in sequence, and shows some.
INTEGER ENUFF,BASE !Some parameters.
INTEGER ENUFF,BASE !Some parameters.
PARAMETER (BASE = 10, ENUFF = 40000) !This should do.
PARAMETER (BASE = 10, ENUFF = 40000) !This should do.
Line 1,448: Line 1,448:
END DO !If there is one, as when N > BASE.
END DO !If there is one, as when N > BASE.
END DO !On to the next result.
END DO !On to the next result.
END !Ends with a new factorial that won't be used.</lang>
END !Ends with a new factorial that won't be used.</syntaxhighlight>
Output: achieved in a few seconds. A larger BASE would give a faster calculation, but would complicate the digit count.
Output: achieved in a few seconds. A larger BASE would give a faster calculation, but would complicate the digit count.
<pre>
<pre>
Line 1,487: Line 1,487:
{{trans|C}}
{{trans|C}}
{{libheader|GMP}}
{{libheader|GMP}}
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


#include "gmp.bi"
#include "gmp.bi"
Line 1,529: Line 1,529:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,578: Line 1,578:
Frink contains efficient algorithms for calculating and caching factorials and this program will work for arbitrarily-large numbers.
Frink contains efficient algorithms for calculating and caching factorials and this program will work for arbitrarily-large numbers.


<lang frink>leftFactorial[n] :=
<syntaxhighlight lang="frink">leftFactorial[n] :=
{
{
sum = 0
sum = 0
Line 1,597: Line 1,597:
println["\nlength of 1000 through 10000"]
println["\nlength of 1000 through 10000"]
for n = 1000 to 10000 step 1000
for n = 1000 to 10000 step 1000
println["$n has " + length[toString[leftFactorial[n]]] + " digits"]</lang>
println["$n has " + length[toString[leftFactorial[n]]] + " digits"]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,639: Line 1,639:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,683: Line 1,683:
}
}
fmt.Println()
fmt.Println()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,702: Line 1,702:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>leftFact :: [Integer]
<syntaxhighlight lang="haskell">leftFact :: [Integer]
leftFact = scanl (+) 0 fact
leftFact = scanl (+) 0 fact


Line 1,721: Line 1,721:
, show $ length . show . (leftFact !!) <$> [1000,2000 .. 10000]
, show $ length . show . (leftFact !!) <$> [1000,2000 .. 10000]
, ""
, ""
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>0 ~ 10:
<pre>0 ~ 10:
Line 1,745: Line 1,745:
{{trans|D}}
{{trans|D}}
The following works in both languages:
The following works in both languages:
<lang>procedure main()
<syntaxhighlight lang="text">procedure main()
every writes(lfact(0 | !10)," ")
every writes(lfact(0 | !10)," ")
write()
write()
Line 1,760: Line 1,760:
every (i := !n, r +:= .f, f *:= .i)
every (i := !n, r +:= .f, f *:= .i)
return r
return r
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,786: Line 1,786:
This could be made more efficient (in terms of machine time), is there a practical application for this? The more efficient machine approach would require a more specialized interface or memory dedicated to caching.
This could be made more efficient (in terms of machine time), is there a practical application for this? The more efficient machine approach would require a more specialized interface or memory dedicated to caching.


<lang J>leftFact=: +/@:!@i."0</lang>
<syntaxhighlight lang="j">leftFact=: +/@:!@i."0</syntaxhighlight>


Task examples:
Task examples:


<lang J> (,. leftFact) i.11
<syntaxhighlight lang="j"> (,. leftFact) i.11
0 0
0 0
1 1
1 1
Line 1,823: Line 1,823:
8000 27749
8000 27749
9000 31678
9000 31678
10000 35656</lang>
10000 35656</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.math.BigInteger;
<syntaxhighlight lang="java">import java.math.BigInteger;


public class LeftFac{
public class LeftFac{
Line 1,858: Line 1,858:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>!0 = 0
<pre>!0 = 0
Line 1,897: Line 1,897:


'''Using builtin arithmetic''':
'''Using builtin arithmetic''':
<lang jq>def left_factorial:
<syntaxhighlight lang="jq">def left_factorial:
reduce range(1; .+1) as $i
reduce range(1; .+1) as $i
# state: [i!, !i]
# state: [i!, !i]
([1,0]; .[1] += .[0] | .[0] *= $i)
([1,0]; .[1] += .[0] | .[0] *= $i)
| .[1];</lang>
| .[1];</syntaxhighlight>


'''Using BigInt.jq''':
'''Using BigInt.jq''':
Line 1,910: Line 1,910:
To compute the lengths of the decimal representation without having to recompute !n,
To compute the lengths of the decimal representation without having to recompute !n,
we also define left_factorial_lengths(gap) to emit [n, ( !n|length) ] when n % gap == 0.
we also define left_factorial_lengths(gap) to emit [n, ( !n|length) ] when n % gap == 0.
<lang jq>import "BigInt" as BigInt;
<syntaxhighlight lang="jq">import "BigInt" as BigInt;


# integer input
# integer input
Line 1,930: Line 1,930:
| (.[1] | tostring | length) as $lf
| (.[1] | tostring | length) as $lf
| if $i % gap == 0 then .[2] += [[$i, $lf]] else . end)
| if $i % gap == 0 then .[2] += [[$i, $lf]] else . end)
| .[2];</lang>
| .[2];</syntaxhighlight>


'''The specific tasks''':
'''The specific tasks''':
<lang sh>((range(0;11), (range(2; 12) * 10)) | "\(.): \(long_left_factorial)"),
<syntaxhighlight lang="sh">((range(0;11), (range(2; 12) * 10)) | "\(.): \(long_left_factorial)"),


(10000 | long_left_factorial_lengths(1000) | .[] | "\(.[0]): length is \(.[1])")</lang>
(10000 | long_left_factorial_lengths(1000) | .[] | "\(.[0]): length is \(.[1])")</syntaxhighlight>


{{out}}
{{out}}
(scrollable)
(scrollable)
<div style="overflow:scroll; height:200px;">
<div style="overflow:scroll; height:200px;">
<lang sh>$ jq -r -n -L . -f Long_left_factorial.jq
<syntaxhighlight lang="sh">$ jq -r -n -L . -f Long_left_factorial.jq
0: 0
0: 0
1: 1
1: 1
Line 1,971: Line 1,971:
8000: length is 27749
8000: length is 27749
9000: length is 31678
9000: length is 31678
10000: length is 35656</lang>
10000: length is 35656</syntaxhighlight>
</div>
</div>


Line 1,977: Line 1,977:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1)
<syntaxhighlight lang="julia">leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1)


@show leftfactorial.(0:10)
@show leftfactorial.(0:10)
@show ndigits.(leftfactorial.(big.(1000:1000:10_000)))</lang>
@show ndigits.(leftfactorial.(big.(1000:1000:10_000)))</syntaxhighlight>


{{out}}
{{out}}
Line 1,987: Line 1,987:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


import java.math.BigInteger
import java.math.BigInteger
Line 2,009: Line 2,009:
for (i in 1000..10000 step 1000)
for (i in 1000..10000 step 1000)
println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits")
println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,051: Line 2,051:


The code can be tested in this wiki page: http://lambdaway.free.fr/lambdawalks/?view=left_factorial
The code can be tested in this wiki page: http://lambdaway.free.fr/lambdawalks/?view=left_factorial
<lang scheme>
<syntaxhighlight lang="scheme">
'''1) defining !n'''
'''1) defining !n'''


Line 2,132: Line 2,132:
Digits of !n(10000) = 35656
Digits of !n(10000) = 35656


</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
Takes about five seconds...
Takes about five seconds...
<lang Lua>-- Lua bindings for GNU bc
<syntaxhighlight lang="lua">-- Lua bindings for GNU bc
require("bc")
require("bc")


Line 2,163: Line 2,163:
for i = 1000, 10000, 1000 do
for i = 1000, 10000, 1000 do
print("!" .. i .. " contains " .. #leftFac(i) .. " digits")
print("!" .. i .. " contains " .. #leftFac(i) .. " digits")
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>!0 = 0
<pre>!0 = 0
Line 2,198: Line 2,198:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>left_factorial := n -> add(k!, k = 1 .. n - 1);
<syntaxhighlight lang="maple">left_factorial := n -> add(k!, k = 1 .. n - 1);
seq(left_factorial(i), i = 1 .. 10);
seq(left_factorial(i), i = 1 .. 10);
seq(left_factorial(i), i = 20 .. 110, 10);
seq(left_factorial(i), i = 20 .. 110, 10);
seq(length(left_factorial(i)), i = 1000 .. 10000, 1000);</lang>
seq(length(left_factorial(i)), i = 1000 .. 10000, 1000);</syntaxhighlight>
{{out}}
{{out}}
<pre>0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113
<pre>0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113
Line 2,210: Line 2,210:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>left[n_] := left[n] = Sum[k!, {k, 0, n - 1}]
<syntaxhighlight lang="mathematica">left[n_] := left[n] = Sum[k!, {k, 0, n - 1}]
Print["left factorials 0 through 10:"]
Print["left factorials 0 through 10:"]
Print[left /@ Range[0, 10] // TableForm]
Print[left /@ Range[0, 10] // TableForm]
Line 2,216: Line 2,216:
Print[left /@ Range[20, 110, 10] // TableForm]
Print[left /@ Range[20, 110, 10] // TableForm]
Print["Digits in left factorials 1,000 through 10,000, by thousands:"]
Print["Digits in left factorials 1,000 through 10,000, by thousands:"]
Print[Length[IntegerDigits[left[#]]] & /@ Range[1000, 10000, 1000] // TableForm]</lang>
Print[Length[IntegerDigits[left[#]]] & /@ Range[1000, 10000, 1000] // TableForm]</syntaxhighlight>
{{out}}
{{out}}
<pre>left factorials 0 through 10:
<pre>left factorials 0 through 10:
Line 2,257: Line 2,257:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import iterutils, bigints
<syntaxhighlight lang="nim">import iterutils, bigints


proc lfact: iterator: BigInt =
proc lfact: iterator: BigInt =
Line 2,282: Line 2,282:
echo "Digits in 1,000 through 10,000 (inclusive) by thousands:"
echo "Digits in 1,000 through 10,000 (inclusive) by thousands:"
for i in lfact().slice(1_000, 10_000, 1_000):
for i in lfact().slice(1_000, 10_000, 1_000):
echo " ", ($i).len</lang>
echo " ", ($i).len</syntaxhighlight>
{{out}}
{{out}}
<pre>first 11:
<pre>first 11:
Line 2,321: Line 2,321:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: leftFact | i | 0 1 rot loop: i [ tuck + swap i * ] drop ;</lang>
<syntaxhighlight lang="oforth">: leftFact | i | 0 1 rot loop: i [ tuck + swap i * ] drop ;</syntaxhighlight>


{{out}}
{{out}}
Line 2,349: Line 2,349:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>lf(n)=sum(k=0,n-1,k!);
<syntaxhighlight lang="parigp">lf(n)=sum(k=0,n-1,k!);
apply(lf, [0..10])
apply(lf, [0..10])
apply(lf, 10*[2..11])
apply(lf, 10*[2..11])
forstep(n=1000,1e4,1000,print1(#digits(lf(n))", "))</lang>
forstep(n=1000,1e4,1000,print1(#digits(lf(n))", "))</syntaxhighlight>
{{out}}
{{out}}
<pre>%1 = [0, 1, 2, 4, 10, 34, 154, 874, 5914, 46234, 409114]
<pre>%1 = [0, 1, 2, 4, 10, 34, 154, 874, 5914, 46234, 409114]
Line 2,363: Line 2,363:
If performance is a concern, this will run over 100x faster by replacing the line "use bigint" with "use Math::GMP qw/:constant/" (after installing that module).
If performance is a concern, this will run over 100x faster by replacing the line "use bigint" with "use Math::GMP qw/:constant/" (after installing that module).


<lang perl>#!perl
<syntaxhighlight lang="perl">#!perl
use 5.010;
use 5.010;
use strict;
use strict;
Line 2,387: Line 2,387:
printf "!%d has %d digits.\n", $_, length leftfact($_) for map $_*1000, 1..10;
printf "!%d has %d digits.\n", $_, length leftfact($_) for map $_*1000, 1..10;


</syntaxhighlight>
</lang>


Since I copied the printf format strings from the Raku implementation,
Since I copied the printf format strings from the Raku implementation,
Line 2,395: Line 2,395:
{{trans|Lua}}
{{trans|Lua}}
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 2,426: Line 2,426:
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1000</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10000</span> <span style="color: #008080;">by</span> <span style="color: #000000;">1000</span> <span style="color: #008080;">do</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"!%d contains %s digits\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1000</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10000</span> <span style="color: #008080;">by</span> <span style="color: #000000;">1000</span> <span style="color: #008080;">do</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"!%d contains %s digits\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"complete (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"complete (%3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,464: Line 2,464:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de n! (N)
<syntaxhighlight lang="picolisp">(de n! (N)
(cache '(NIL) N
(cache '(NIL) N
(if (> 2 N) 1
(if (> 2 N) 1
Line 2,481: Line 2,481:
(prinl "length of 1000 - 10000")
(prinl "length of 1000 - 10000")
(pril (mapcar 'length (mapcar '!n (range 1000 10000 1000))))
(pril (mapcar 'length (mapcar '!n (range 1000 10000 1000))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang>0-10
<syntaxhighlight lang="text">0-10
1
1
1
1
Line 2,517: Line 2,517:
31678
31678
35656
35656
</syntaxhighlight>
</lang>


=={{header|PL/I}}==
=={{header|PL/I}}==
Line 2,524: Line 2,524:
Results are shown for the first 11 integers, as required;
Results are shown for the first 11 integers, as required;
then for the integers from 20 through 30 only, because factorials for n = 40 and larger are not possible.
then for the integers from 20 through 30 only, because factorials for n = 40 and larger are not possible.
<lang pli>lf: procedure (n) returns (fixed decimal (31) );
<syntaxhighlight lang="pli">lf: procedure (n) returns (fixed decimal (31) );
declare n fixed binary;
declare n fixed binary;
declare (s, f) fixed (31);
declare (s, f) fixed (31);
Line 2,546: Line 2,546:
end;
end;


end left_factorials;</lang>
end left_factorials;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,575: Line 2,575:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function left-factorial ([BigInt]$n) {
function left-factorial ([BigInt]$n) {
[BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One)
[BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One)
Line 2,602: Line 2,602:
else {"!$i has $digits digit"}
else {"!$i has $digits digit"}
}
}
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,644: Line 2,644:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>leftfact(N):-
<syntaxhighlight lang="prolog">leftfact(N):-
leftfact(N, 0, 0, 1).
leftfact(N, 0, 0, 1).


Line 2,665: Line 2,665:
main:-
main:-
leftfact(10001).</lang>
leftfact(10001).</syntaxhighlight>


{{out}}
{{out}}
Line 2,703: Line 2,703:


=={{header|Python}}==
=={{header|Python}}==
<lang python>from itertools import islice
<syntaxhighlight lang="python">from itertools import islice


def lfact():
def lfact():
Line 2,717: Line 2,717:
print(lf)
print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r'
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r'
% [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )</lang>
% [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )</syntaxhighlight>


{{out}}
{{out}}
Line 2,743: Line 2,743:


{{Trans|Haskell}}
{{Trans|Haskell}}
<lang python>'''Left factorials'''
<syntaxhighlight lang="python">'''Left factorials'''


from itertools import (accumulate, chain, count, islice)
from itertools import (accumulate, chain, count, islice)
Line 2,834: Line 2,834:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Terms 0 thru 10 inclusive:
<pre>Terms 0 thru 10 inclusive:
Line 2,856: Line 2,856:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n )
<syntaxhighlight lang="quackery"> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n )


[ 0 swap times [ i ! + ] ] is !n ( n --> n )
[ 0 swap times [ i ! + ] ] is !n ( n --> n )
Line 2,868: Line 2,868:
say "Digits in 1,000 through 10,000 by thousands:" cr
say "Digits in 1,000 through 10,000 by thousands:" cr
10 times [ i^ 1+ 1000 * !n number$ size echo cr ]
10 times [ i^ 1+ 1000 * !n number$ size echo cr ]
cr</lang>
cr</syntaxhighlight>


{{out}}
{{out}}
Line 2,901: Line 2,901:
=={{header|R}}==
=={{header|R}}==
===Imperative solution===
===Imperative solution===
<lang rsplus>library(gmp)
<syntaxhighlight lang="rsplus">library(gmp)


left_factorial <- function(n) {
left_factorial <- function(n) {
Line 2,932: Line 2,932:
cat("!",n," has ",digit_count(left_factorial(n))," digits\n", sep = "")
cat("!",n," has ",digit_count(left_factorial(n))," digits\n", sep = "")
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,968: Line 2,968:
===Vectorization solution===
===Vectorization solution===
Due to vectorization, these sorts of problems are R's bread and butter. The only challenge comes from making sure that R plays nice with objects from the gmp library.
Due to vectorization, these sorts of problems are R's bread and butter. The only challenge comes from making sure that R plays nice with objects from the gmp library.
<lang rsplus>library(gmp)
<syntaxhighlight lang="rsplus">library(gmp)
leftFact <- function(numbs)
leftFact <- function(numbs)
{
{
Line 2,985: Line 2,985:
#Task 3
#Task 3
inputs<-seq(1000, 10000, by = 1000)
inputs<-seq(1000, 10000, by = 1000)
print(data.frame(Digits = sapply(leftFact(inputs), nchar), row.names = paste0("!", inputs)))</lang>
print(data.frame(Digits = sapply(leftFact(inputs), nchar), row.names = paste0("!", inputs)))</syntaxhighlight>


{{out}}
{{out}}
Line 3,030: Line 3,030:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define ! (let ((rv# (make-hash))) (λ (n) (hash-ref! rv# n (λ () (if (= n 0) 1 (* n (! (- n 1)))))))))
(define ! (let ((rv# (make-hash))) (λ (n) (hash-ref! rv# n (λ () (if (= n 0) 1 (* n (! (- n 1)))))))))


Line 3,046: Line 3,046:
"Display the length (in decimal digits) of the left factorials for:"
"Display the length (in decimal digits) of the left factorials for:"
"1,000, 2,000 through 10,000 (inclusive), by thousands."
"1,000, 2,000 through 10,000 (inclusive), by thousands."
(pretty-format (for/list ((i (in-range 1000 10001 1000))) (add1 (order-of-magnitude (!n i))))))</lang>
(pretty-format (for/list ((i (in-range 1000 10001 1000))) (add1 (order-of-magnitude (!n i))))))</syntaxhighlight>


{{out}}
{{out}}
Line 3,072: Line 3,072:
Implement left factorial as a prefix !. Note that this redefines the core prefix ! (not) function.
Implement left factorial as a prefix !. Note that this redefines the core prefix ! (not) function.


<lang perl6>sub prefix:<!> ($k) { (constant l = 0, |[\+] 1, (|[\*] 1..*))[$k] }
<syntaxhighlight lang="raku" line>sub prefix:<!> ($k) { (constant l = 0, |[\+] 1, (|[\*] 1..*))[$k] }


$ = !10000; # Pre-initialize
$ = !10000; # Pre-initialize


.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d = %s", $_, !$_ };
.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d = %s", $_, !$_ };
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars !$_ };</lang>
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars !$_ };</syntaxhighlight>
{{out}}
{{out}}
<pre>!0 = 0
<pre>!0 = 0
Line 3,111: Line 3,111:
!10000 has 35656 digits.</pre>
!10000 has 35656 digits.</pre>
If you would rather not override prefix ! operator and you can live with just defining lazy lists and indexing into them, this should suffice; (and is in fact very slightly faster than the first example since it avoids routine dispatch overhead):
If you would rather not override prefix ! operator and you can live with just defining lazy lists and indexing into them, this should suffice; (and is in fact very slightly faster than the first example since it avoids routine dispatch overhead):
<lang perl6>constant leftfact = 0, |[\+] 1, (|[\*] 1..*);
<syntaxhighlight lang="raku" line>constant leftfact = 0, |[\+] 1, (|[\*] 1..*);


$ = leftfact[10000]; # Pre-initialize
$ = leftfact[10000]; # Pre-initialize


.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d = %s", $_, leftfact[$_] };
.say for ( 0 … 10, 20 … 110 ).hyper(:4batch).map: { sprintf "!%d = %s", $_, leftfact[$_] };
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars leftfact[$_] };</lang>
.say for (1000, 2000 … 10000).hyper(:4batch).map: { sprintf "!%d has %d digits.", $_, chars leftfact[$_] };</syntaxhighlight>


Same output.
Same output.
Line 3,124: Line 3,124:


This is possible because there will be a number of trailing zeros which allow a floating point number to be converted to an integer.
This is possible because there will be a number of trailing zeros which allow a floating point number to be converted to an integer.
<lang rexx>/*REXX program computes/display the left factorial (or its dec. width) of N (or a range)*/
<syntaxhighlight lang="rexx">/*REXX program computes/display the left factorial (or its dec. width) of N (or a range)*/
parse arg bot top inc . /*obtain optional arguments from the CL*/
parse arg bot top inc . /*obtain optional arguments from the CL*/
if bot=='' | bot=="," then bot= 1 /*Not specified: Then use the default.*/
if bot=='' | bot=="," then bot= 1 /*Not specified: Then use the default.*/
Line 3,143: Line 3,143:
$= $ + ! /*add the factorial ───► L! sum. */
$= $ + ! /*add the factorial ───► L! sum. */
end /*#*/ /* [↑] handles gihugeic numbers. */
end /*#*/ /* [↑] handles gihugeic numbers. */
return $ /*return the sum (L!) to the invoker.*/</lang>
return $ /*return the sum (L!) to the invoker.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 0 &nbsp; 10 </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 0 &nbsp; 10 </tt>}}
<pre>
<pre>
Line 3,186: Line 3,186:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
a = leftFact(0,10,1)
a = leftFact(0,10,1)
see "" + a + nl
see "" + a + nl
Line 3,202: Line 3,202:
else see "" + i + " " + leftFact + nl ok
else see "" + i + " " + leftFact + nl ok
next
next
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>left_fact = Enumerator.new do |y|
<syntaxhighlight lang="ruby">left_fact = Enumerator.new do |y|
f, lf = 1, 0
f, lf = 1, 0
1.step do |n|
1.step do |n|
Line 3,212: Line 3,212:
f *= n
f *= n
end
end
end</lang>
end</syntaxhighlight>
'''Test:'''
'''Test:'''
<lang ruby>tens = 20.step(110, 10)
<syntaxhighlight lang="ruby">tens = 20.step(110, 10)
thousands = 1000.step(10_000, 1000)
thousands = 1000.step(10_000, 1000)


Line 3,225: Line 3,225:
puts "!#{n} has #{lf.to_s.size} digits"
puts "!#{n} has #{lf.to_s.size} digits"
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>!0 = 0
<pre>!0 = 0
Line 3,261: Line 3,261:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang Runbasic>a = lftFct(0,10,1)
<syntaxhighlight lang="runbasic">a = lftFct(0,10,1)
a = lftFct(20,110,10)
a = lftFct(20,110,10)
a = lftFct(1000,10000,1000)
a = lftFct(1000,10000,1000)
Line 3,280: Line 3,280:
end if
end if
next i
next i
end function</lang>Output:
end function</syntaxhighlight>Output:
<pre>------ From 0 --To-> 10 Step 1 -------
<pre>------ From 0 --To-> 10 Step 1 -------
0 1
0 1
Line 3,319: Line 3,319:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
#[cfg(target_pointer_width = "64")]
#[cfg(target_pointer_width = "64")]
type USingle = u32;
type USingle = u32;
Line 3,443: Line 3,443:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,482: Line 3,482:
This solution uses the arbitrary precision integers from the rug crate,
This solution uses the arbitrary precision integers from the rug crate,
which uses GMP under the covers.
which uses GMP under the covers.
<lang rust>// [dependencies]
<syntaxhighlight lang="rust">// [dependencies]
// rug = "1.9"
// rug = "1.9"


Line 3,513: Line 3,513:
println!("length of !{} = {}", i, n.to_string().len());
println!("length of !{} = {}", i, n.to_string().len());
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,554: Line 3,554:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object LeftFactorial extends App {
<syntaxhighlight lang="scala">object LeftFactorial extends App {


// this part isn't really necessary, it just shows off Scala's ability
// this part isn't really necessary, it just shows off Scala's ability
Line 3,574: Line 3,574:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,617: Line 3,617:
and (iota 5 100 2) produces a list (100 102 104 106 108)
and (iota 5 100 2) produces a list (100 102 104 106 108)


<lang scheme>
<syntaxhighlight lang="scheme">
(import (scheme base) ;; library imports in R7RS style
(import (scheme base) ;; library imports in R7RS style
(scheme write)
(scheme write)
Line 3,645: Line 3,645:
(lambda (i) (show i (string-length (number->string (left-factorial i)))))
(lambda (i) (show i (string-length (number->string (left-factorial i)))))
(iota 10 1000 1000))
(iota 10 1000 1000))
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";


Line 3,683: Line 3,683:
end for;
end for;
writeln;
writeln;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,716: Line 3,716:
=={{header|Sidef}}==
=={{header|Sidef}}==
Built-in:
Built-in:
<lang ruby>say 20.of { .left_factorial }</lang>
<syntaxhighlight lang="ruby">say 20.of { .left_factorial }</syntaxhighlight>


Straightforward:
Straightforward:
<lang ruby>func left_factorial(n) {
<syntaxhighlight lang="ruby">func left_factorial(n) {
^n -> sum { _! }
^n -> sum { _! }
}</lang>
}</syntaxhighlight>


Alternatively, using ''Range.reduce()'':
Alternatively, using ''Range.reduce()'':
<lang ruby>func left_factorial(n) {
<syntaxhighlight lang="ruby">func left_factorial(n) {
^n -> reduce({ |a,b| a + b! }, 0)
^n -> reduce({ |a,b| a + b! }, 0)
}</lang>
}</syntaxhighlight>


A faster approach:
A faster approach:
<lang ruby>func left_factorial(n) {
<syntaxhighlight lang="ruby">func left_factorial(n) {
static cached = 0
static cached = 0
static factorial = 1
static factorial = 1
Line 3,746: Line 3,746:


leftfact
leftfact
}</lang>
}</syntaxhighlight>


Completing the task:
Completing the task:
<lang ruby>for n in (0..10, 20..110 `by` 10) {
<syntaxhighlight lang="ruby">for n in (0..10, 20..110 `by` 10) {
printf("!%d = %s\n", n, left_factorial(n))
printf("!%d = %s\n", n, left_factorial(n))
}
}
Line 3,755: Line 3,755:
for n in (1000..10000 `by` 1000) {
for n in (1000..10000 `by` 1000) {
printf("!%d has %d digits.\n", n, left_factorial(n).len)
printf("!%d has %d digits.\n", n, left_factorial(n).len)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,792: Line 3,792:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>
<syntaxhighlight lang="sml">
(* reuse earlier factorial calculations in dfac, apply to listed arguments in cumlfac *)
(* reuse earlier factorial calculations in dfac, apply to listed arguments in cumlfac *)
(* example: left factorial n, is #3 (dfac (0,n-1,1,1) ) *)
(* example: left factorial n, is #3 (dfac (0,n-1,1,1) ) *)
Line 3,822: Line 3,822:
List.app (fn triple :int*int*int =>
List.app (fn triple :int*int*int =>
print( Int.toString (1+ #1 triple ) ^ " : " ^ Int.toString (size(Int.toString (#3 triple ))) ^" \n" ) ) (List.drop(result,21) );
print( Int.toString (1+ #1 triple ) ^ " : " ^ Int.toString (size(Int.toString (#3 triple ))) ^" \n" ) ) (List.drop(result,21) );
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,864: Line 3,864:
{{libheader|AttaSwift BigInt}}
{{libheader|AttaSwift BigInt}}


<lang swift>import BigInt
<syntaxhighlight lang="swift">import BigInt


func factorial<T: BinaryInteger>(_ n: T) -> T {
func factorial<T: BinaryInteger>(_ n: T) -> T {
Line 3,900: Line 3,900:
for i in stride(from: BigInt(2000), through: 10_000, by: 1000) {
for i in stride(from: BigInt(2000), through: 10_000, by: 1000) {
print("!\(i) = \((!i).description.count) digit number")
print("!\(i) = \((!i).description.count) digit number")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,940: Line 3,940:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc leftfact {n} {
<syntaxhighlight lang="tcl">proc leftfact {n} {
set s 0
set s 0
for {set i [set f 1]} {$i <= $n} {incr i} {
for {set i [set f 1]} {$i <= $n} {incr i} {
Line 3,954: Line 3,954:
for {set i 1000} {$i <= 10000} {incr i 1000} {
for {set i 1000} {$i <= 10000} {incr i 1000} {
puts "!$i has [string length [leftfact $i]] digits"
puts "!$i has [string length [leftfact $i]] digits"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,993: Line 3,993:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt
import "/big" for BigInt
import "/big" for BigInt


Line 4,022: Line 4,022:
}
}
System.print("\nLengths of left factorals from 1000 to 10000 by thousands:")
System.print("\nLengths of left factorals from 1000 to 10000 by thousands:")
for (i in 1..10) Fmt.print(" !$-5d -> $5s", i * 1000, lfacts[i].toString.count)</lang>
for (i in 1..10) Fmt.print(" !$-5d -> $5s", i * 1000, lfacts[i].toString.count)</syntaxhighlight>


{{out}}
{{out}}
Line 4,056: Line 4,056:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|D}}
{{trans|D}}
<lang zkl>var BN=Import("zklBigNum");
<syntaxhighlight lang="zkl">var BN=Import("zklBigNum");


fcn leftFact(n){
fcn leftFact(n){
[1..n].reduce(fcn(p,n,rf){ p+=rf.value; rf.set(rf.value*n); p },
[1..n].reduce(fcn(p,n,rf){ p+=rf.value; rf.set(rf.value*n); p },
BN(0),Ref(BN(1)));
BN(0),Ref(BN(1)));
}</lang>
}</syntaxhighlight>
<lang zkl>println("First 11 left factorials:\n", [0..10].apply(leftFact));
<syntaxhighlight lang="zkl">println("First 11 left factorials:\n", [0..10].apply(leftFact));
lfs:=[20..111,10].apply(leftFact);
lfs:=[20..111,10].apply(leftFact);
println(("\n20 through 110 (inclusive) by tens:\n" +
println(("\n20 through 110 (inclusive) by tens:\n" +
Line 4,068: Line 4,068:


println("Digits in 1,000 through 10,000 by thousands:\n",
println("Digits in 1,000 through 10,000 by thousands:\n",
[0d1_000..0d10_000, 1000].pump(List,fcn(n){leftFact(n).toString().len()}));</lang>
[0d1_000..0d10_000, 1000].pump(List,fcn(n){leftFact(n).toString().len()}));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>