<p>I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language.</p>
<h2>Ideas:</h2>
<ul>
<li>Procedural</li>
<li>Functional</li>
<li>Object Oriented</li>
<li>One liners</li>
<li>Obfuscated</li>
<li>Oddball</li>
<li>Bad Code</li>
<li><a href="http://en.wikipedia.org/wiki/Polyglot_%28computing%29" rel="nofollow noreferrer">Polyglot</a></li>
</ul>
<p>Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages.</p>
<p>Please limit it to one example per entry.
I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post.</p>
<p>The only real requirement is it must find the factorial of a given argument, in all languages represented.</p>
<h1>Be Creative!</h1>
<h2>Recommended Guideline:</h2>
<pre>
# Language Name: Optional Style type

   - Optional bullet points

    Code Goes Here

Other informational text goes here
</pre>
<p>I will ocasionally go along and edit any answer that does not have decent formatting.</p>

[{'answer_id': 23932, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 2, 'selected': False, 'text': '<h1>Perl 6: Functional</h1>\n\n<pre><code>multi factorial ( Int $n where { $n &lt;= 0 } ){\n  return 1;\n}\nmulti factorial ( Int $n ){\n   return $n * factorial( $n-1 );\n}\n</code></pre>\n\n<p>\nThis will also work:</p>\n\n<pre><code>multi factorial(0) { 1 }\nmulti factorial(Int $n) { $n * factorial($n - 1) }\n</code></pre>\n\n<p><em>Check <a href="http://use.perl.org/~JonathanWorthington/journal/39196?from=StackOverflow" rel="nofollow noreferrer">Jonathan Worthington\'s</a> journal on <a href="http://use.perl.org" rel="nofollow noreferrer">use.perl.org</a>, for more information about the last example.</em></p>\n'}, {'answer_id': 23936, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 2, 'selected': False, 'text': '<h1>Perl 6:Procedural</h1>\n<pre><code>sub factorial ( int $n ){\n\n  my $result = 1;\n\n  loop ( ; $n &gt; 0; $n-- ){\n\n    $result *= $n;\n\n  }\n\n  return $result;\n}\n</code></pre>\n'}, {'answer_id': 23938, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 2, 'selected': False, 'text': '<p>C:</p>\n\n<p>Edit: Actually C++ I guess, because of the variable declaration in the for loop.</p>\n\n<pre><code> int factorial(int x) {\n      int product = 1;\n\n      for (int i = x; i &gt; 0; i--) {\n           product *= i;\n      }\n\n      return product;\n }\n</code></pre>\n'}, {'answer_id': 23958, 'author': 'AnnanFay', 'author_id': 2118, 'author_profile': 'https://Stackoverflow.com/users/2118', 'pm_score': 2, 'selected': False, 'text': "<h1>Javascript:</h1>\n<pre><code>factorial = function( n )\n{\n   return n &gt; 0 ? n * factorial( n - 1 ) : 1;\n}\n</code></pre>\n<p>I'm not sure what a Factorial is but that does what the other programs do in javascript.</p>\n"}, {'answer_id': 23969, 'author': 'olliej', 'author_id': 784, 'author_profile': 'https://Stackoverflow.com/users/784', 'pm_score': 4, 'selected': False, 'text': '<p>Haskell:</p>\n\n<pre><code>ones = 1 : ones\nintegers   = head ones     : zipWith (+) integers   (tail ones)\nfactorials = head integers : zipWith (*) factorials (tail integers)\n</code></pre>\n'}, {'answer_id': 23976, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Scheme</strong></p>\n\n<p>Here is a simple recursive definition:</p>\n\n<pre><code>(define (factorial x)\n  (if (= x 0) 1\n      (* x (factorial (- x 1)))))\n</code></pre>\n\n<p>In Scheme tail-recursive functions use constant stack space. Here is a version of factorial that is tail-recursive:</p>\n\n<pre><code>(define factorial\n  (letrec ((fact (lambda (x accum)\n                   (if (= x 0) accum\n                       (fact (- x 1) (* accum x))))))\n    (lambda (x)\n      (fact x 1))))\n</code></pre>\n'}, {'answer_id': 23979, 'author': 'Niyaz', 'author_id': 184, 'author_profile': 'https://Stackoverflow.com/users/184', 'pm_score': 1, 'selected': False, 'text': '<p>C++</p>\n\n<pre><code>factorial(int n)\n{\n    for(int i=1, f = 1; i&lt;=n; i++)\n        f *= i;\n    return f;\n}\n</code></pre>\n'}, {'answer_id': 23982, 'author': 'Imran', 'author_id': 1897, 'author_profile': 'https://Stackoverflow.com/users/1897', 'pm_score': 3, 'selected': False, 'text': '<p><strong>C/C++</strong>: Procedural</p>\n\n<pre><code>unsigned long factorial(int n)\n{\n    unsigned long factorial = 1;\n    int i;\n\n    for (i = 2; i &lt;= n; i++)\n        factorial *= i;\n\n    return factorial;\n}\n</code></pre>\n\n<p><strong>PHP</strong>: Procedural</p>\n\n<pre><code>function factorial($n)\n{\n    for ($factorial = 1, $i = 2; $i &lt;= $n; $i++)\n        $factorial *= $i;\n\n    return $factorial;\n}\n</code></pre>\n\n<p><a href="https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages#23979">@Niyaz</a>: You didn\'t specify return type for the function</p>\n'}, {'answer_id': 23989, 'author': 'Ed.', 'author_id': 522, 'author_profile': 'https://Stackoverflow.com/users/522', 'pm_score': 7, 'selected': False, 'text': "<h2>lolcode:</h2>\n<p>sorry I couldn't resist xD</p>\n<pre><code>HAI\nCAN HAS STDIO?\nI HAS A VAR\nI HAS A INT\nI HAS A CHEEZBURGER\nI HAS A FACTORIALNUM\nIM IN YR LOOP\n    UP VAR!!1\n    TIEMZD INT!![CHEEZBURGER]\n    UP FACTORIALNUM!!1\n    IZ VAR BIGGER THAN FACTORIALNUM? GTFO\nIM OUTTA YR LOOP\nU SEEZ INT\nKTHXBYE    \n</code></pre>\n"}, {'answer_id': 24296, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 3, 'selected': False, 'text': '<h1><a href="http://www.digitalmars.com/d/2.0/template-comparison.html" rel="nofollow noreferrer">D Templates: Functional</a></h1>\n\n<pre><code>template factorial(int n : 1)\n{\n  const factorial = 1;\n}\n\ntemplate factorial(int n)\n{\n  const factorial =\n     n * factorial!(n-1);\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>template factorial(int n)\n{\n  static if(n == 1)\n    const factorial = 1;\n  else \n    const factorial =\n       n * factorial!(n-1);\n}\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>factorial!(5)\n</code></pre>\n'}, {'answer_id': 24300, 'author': 'Artur Carvalho', 'author_id': 1013, 'author_profile': 'https://Stackoverflow.com/users/1013', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Python:</strong></p>\n\n<p>Recursive</p>\n\n<pre><code>def fact(x): \n    return (1 if x==0 else x * fact(x-1))\n</code></pre>\n\n<p>Using iterator</p>\n\n<pre><code>import operator\n\ndef fact(x):\n    return reduce(operator.mul, xrange(1, x+1))\n</code></pre>\n'}, {'answer_id': 24343, 'author': 'John with waffle', 'author_id': 279, 'author_profile': 'https://Stackoverflow.com/users/279', 'pm_score': 2, 'selected': False, 'text': "<p>two of many Mathematica solutions (although ! is built-in and efficient):</p>\n\n<pre><code>(* returns pure function *)\n(FixedPoint[(If[#[[2]]&gt;1,{#[[1]]*#[[2]],#[[2]]-1},#])&amp;,{1,n}][[1]])&amp;\n\n(* not using built-in, returns pure function, don't use: might build 1..n list *)\n(Times @@ Range[#])&amp;\n</code></pre>\n"}, {'answer_id': 24524, 'author': 'Josh Brown', 'author_id': 2030, 'author_profile': 'https://Stackoverflow.com/users/2030', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Java</strong>: functional</p>\n\n<pre><code>int factorial(int x) {\n    return x == 0 ? 1 : x * factorial(x-1);\n}\n</code></pre>\n'}, {'answer_id': 27114, 'author': 'John with waffle', 'author_id': 279, 'author_profile': 'https://Stackoverflow.com/users/279', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Mathematica</strong> : using pure recursive functions</p>\n\n<pre><code>(If[#&gt;1,# #0[#-1],1])&amp;\n</code></pre>\n'}, {'answer_id': 27142, 'author': 'krujos', 'author_id': 511, 'author_profile': 'https://Stackoverflow.com/users/511', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Ruby: functional</strong></p>\n\n<pre><code>def factorial(n)\n    return 1 if n == 1\n    n * factorial(n -1)\nend\n</code></pre>\n'}, {'answer_id': 27149, 'author': 'Jon Ericson', 'author_id': 1438, 'author_profile': 'https://Stackoverflow.com/users/1438', 'pm_score': 2, 'selected': False, 'text': "<h1>Lua</h1>\n\n<pre><code>function factorial (n)\n  if (n &lt;= 1) then return 1 end\n  return n*factorial(n-1)\nend\n</code></pre>\n\n<p>And here is a stack overflow caught in the wild:</p>\n\n<pre><code>&gt; print (factorial(234132))\nstdin:3: stack overflow\nstack traceback:\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    ...\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:3: in function 'factorial'\n    stdin:1: in main chunk\n    [C]: ?\n</code></pre>\n"}, {'answer_id': 37416, 'author': 'Chris Smith', 'author_id': 322, 'author_profile': 'https://Stackoverflow.com/users/322', 'pm_score': 3, 'selected': False, 'text': '<h1>F#: Functional</h1>\n\n<h3>Straight forward:</h3>\n\n<pre><code>let rec fact x = \n    if   x &lt; 0 then failwith "Invalid value."\n    elif x = 0 then 1\n    else x * fact (x - 1)\n</code></pre>\n\n<h3>Getting fancy:</h3>\n\n<pre><code>let fact x = [1 .. x] |&gt; List.fold_left ( * ) 1\n</code></pre>\n'}, {'answer_id': 37421, 'author': 'Andres', 'author_id': 1815, 'author_profile': 'https://Stackoverflow.com/users/1815', 'pm_score': 1, 'selected': False, 'text': '<h1>Haskell: Functional</h1>\n\n<pre><code> fact 0 = 1\n fact n = n * fact (n-1)\n</code></pre>\n'}, {'answer_id': 37427, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 6, 'selected': False, 'text': '<h1>C++: Template Metaprogramming</h1>\n\n<p>Uses the classic enum hack.</p>\n\n<pre><code>template&lt;unsigned int n&gt;\nstruct factorial {\n    enum { result = n * factorial&lt;n - 1&gt;::result };\n};\n\ntemplate&lt;&gt;\nstruct factorial&lt;0&gt; {\n    enum { result = 1 };\n};\n</code></pre>\n\n<p>Usage.</p>\n\n<pre><code>const unsigned int x = factorial&lt;4&gt;::result;\n</code></pre>\n\n<p>Factorial is calculated completely at compile time based on the template parameter n. Therefore, factorial&lt;4>::result is a constant once the compiler has done its work.</p>\n'}, {'answer_id': 37459, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 1, 'selected': False, 'text': '<p>This one not only calculates n!, it is also O(n!). It may have problems if you want to calculate anything "big" though.</p>\n\n<pre><code>long f(long n)\n{\n    long r=1;\n    for (long i=1; i&lt;n; i++)\n        r=r*i;\n    return r;\n}\n\nlong factorial(long n)\n{\n    // iterative implementation should be efficient\n    long result;\n    for (long i=0; i&lt;f(n); i++)\n        result=result+1;\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 37576, 'author': 'Chris de Vries', 'author_id': 3836, 'author_profile': 'https://Stackoverflow.com/users/3836', 'pm_score': 4, 'selected': False, 'text': '<h1>x86-64 Assembly: Procedural</h1>\n\n<p>You can call this from C (only tested with GCC on linux amd64).\nAssembly was assembled with nasm.</p>\n\n<pre><code>section .text\n    global factorial\n; factorial in x86-64 - n is passed in via RDI register\n; takes a 64-bit unsigned integer\n; returns a 64-bit unsigned integer in RAX register\n; C declaration in GCC:\n;   extern unsigned long long factorial(unsigned long long n);\nfactorial:\n    enter 0,0\n    ; n is placed in rdi by caller\n    mov rax, 1 ; factorial = 1\n    mov rcx, 2 ; i = 2\nloopstart:\n    cmp rcx, rdi\n    ja loopend\n    mul rcx ; factorial *= i\n    inc rcx\n    jmp loopstart\nloopend:\n    leave\n    ret\n</code></pre>\n'}, {'answer_id': 37647, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': "<h1>Visual Basic: Linq</h1>\n\n<pre><code>&lt;Extension()&gt; _\nPublic Function Product(ByVal xs As IEnumerable(Of Integer)) As Integer\n    Return xs.Aggregate(1, Function(a, b) a * b)\nEnd Function\n\nPublic Function Fact(ByVal n As Integer) As Integer\n    Return Aggregate x In Enumerable.Range(1, n) Into Product()\nEnd Function\n</code></pre>\n\n<p>This shows how to use the <code>Aggregate</code> keyword in VB. <strong>C# can't do this</strong> (although C# can of course call the extension method directly).</p>\n"}, {'answer_id': 37664, 'author': 'Jeff Hillman', 'author_id': 3950, 'author_profile': 'https://Stackoverflow.com/users/3950', 'pm_score': 3, 'selected': False, 'text': "<p>PowerShell</p>\n\n<pre><code>function factorial( [int] $n ) \n{ \n    $result = 1; \n\n    if ( $n -gt 1 ) \n    { \n        $result = $n * ( factorial ( $n - 1 ) ) \n    } \n\n    $result \n}\n</code></pre>\n\n<p>Here's a one-liner:</p>\n\n<pre><code>$n..1 | % {$result = 1}{$result *= $_}{$result}\n</code></pre>\n"}, {'answer_id': 37736, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<h1>Recursive Prolog</h1>\n\n<pre><code>fac(0,1).\nfac(N,X) :- N1 is N -1, fac(N1, T), X is N * T.\n</code></pre>\n\n<h1>Tail Recursive Prolog</h1>\n\n<pre><code>fac(0,N,N).\nfac(X,N,T) :- A is N * X, X1 is X - 1, fac(X1,A,T).\nfac(N,T) :- fac(N,1,T).\n</code></pre>\n'}, {'answer_id': 37814, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Bourne Shell: Functional</strong></p>\n\n<pre><code>factorial() {\n  if [ $1 -eq 0 ]\n  then\n    echo 1\n    return\n  fi\n\n  a=`expr $1 - 1`\n  expr $1 \\* `factorial $a`\n}\n</code></pre>\n\n<p>Also works for Korn Shell and Bourne Again Shell. :-)</p>\n'}, {'answer_id': 37847, 'author': 'Alexander Stolz', 'author_id': 2450, 'author_profile': 'https://Stackoverflow.com/users/2450', 'pm_score': 1, 'selected': False, 'text': '<p><strong><em>Lisp recursive:</em></strong></p>\n\n<pre><code>(defun factorial (x) \n   (if (&lt;= x 1) \n       1 \n       (* x (factorial (- x 1)))))\n</code></pre>\n'}, {'answer_id': 37906, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 1, 'selected': False, 'text': '<p><strong>JavaScript</strong>\nUsing anonymous functions:</p>\n\n<pre><code>var f = function(n){\n  if(n&gt;1){\n    return arguments.callee(n-1)*n;\n  }\n  return 1;\n}\n</code></pre>\n'}, {'answer_id': 38369, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 3, 'selected': False, 'text': '<p>Oddball examples? What about using the gamma function! Since, <code>Gamma n = (n-1)!</code>.</p>\n\n<h2>OCaml: Using Gamma</h2>\n\n<pre><code>let rec gamma z =\n    let pi = 4.0 *. atan 1.0 in\n    if z &lt; 0.5 then\n        pi /. ((sin (pi*.z)) *. (gamma (1.0 -. z)))\n    else\n        let consts = [| 0.99999999999980993; 676.5203681218851; -1259.1392167224028;\n                        771.32342877765313; -176.61502916214059; 12.507343278686905;\n                 -0.13857109526572012; 9.9843695780195716e-6; 1.5056327351493116e-7;\n                     |] \n        in\n        let z = z -. 1.0 in\n        let results = Array.fold_right \n                          (fun x y -&gt; x +. y)\n                          (Array.mapi \n                              (fun i x -&gt; if i = 0 then x else x /. (z+.(float i)))\n                              consts\n                          )\n                          0.0\n        in\n        let x = z +. (float (Array.length consts)) -. 1.5 in\n        let final = (sqrt (2.0*.pi)) *. \n                    (x ** (z+.0.5)) *.\n                    (exp (-.x)) *. result\n        in\n        final\n\nlet factorial_gamma n = int_of_float (gamma (float (n+1)))\n</code></pre>\n'}, {'answer_id': 38399, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 1, 'selected': False, 'text': "<h1>C: One liner, procedural</h1>\n\n<pre><code>int f(int n) { for (int i = n - 1; i &gt; 0; n *= i, i--); return n ? n : 1; }\n</code></pre>\n\n<p>I used int's for brevity; use other types to support larger numbers.</p>\n"}, {'answer_id': 38423, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 3, 'selected': False, 'text': '<h1>BASIC: old school</h1>\n\n<pre><code>10 HOME\n20 INPUT N\n30 LET ANS = 1\n40 FOR I = 1 TO N\n50   ANS = ANS * I\n60 NEXT I\n70 PRINT ANS\n</code></pre>\n'}, {'answer_id': 38484, 'author': 'rcreswick', 'author_id': 3446, 'author_profile': 'https://Stackoverflow.com/users/3446', 'pm_score': 3, 'selected': False, 'text': '<h1>Java 1.6: recursive, memoized (for subsequent calls)</h1>\n<pre><code>private static Map&lt;BigInteger, BigInteger&gt; _results = new HashMap()\n\npublic static BigInteger factorial(BigInteger n){\n    if (0 &gt;= n.compareTo(BigInteger.ONE))\n       return BigInteger.ONE.max(n);\n    if (_results.containsKey(n))\n       return _results.get(n);\n    BigInteger result = factorial(n.subtract(BigInteger.ONE)).multiply(n);\n    _results.put(n, result);\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 38673, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 2, 'selected': False, 'text': '<h1>Scheme : Functional - Tail Recursive</h1>\n\n<pre><code>(define (factorial n)\n  (define (fac-times n acc)\n    (if (= n 0)\n        acc\n        (fac-times (- n 1) (* acc n))))\n  (if (&lt; n 0)\n      (display "Wrong argument!")\n      (fac-times n 1)))\n</code></pre>\n'}, {'answer_id': 38717, 'author': 'Jeff Hillman', 'author_id': 3950, 'author_profile': 'https://Stackoverflow.com/users/3950', 'pm_score': 3, 'selected': False, 'text': '<p>Batch (NT):</p>\n\n<pre><code>@echo off\n\nset n=%1\nset result=1\n\nfor /l %%i in (%n%, -1, 1) do (\n    set /a result=result * %%i\n)\n\necho %result%\n</code></pre>\n\n<p>Usage: \nC:>factorial.bat 15</p>\n'}, {'answer_id': 38734, 'author': 'grom', 'author_id': 486, 'author_profile': 'https://Stackoverflow.com/users/486', 'pm_score': 0, 'selected': False, 'text': "<h1>Haskell : Functional - Tail Recursive</h1>\n\n<pre><code>factorial n = factorial' n 1\n\nfactorial' 0 a = a\nfactorial' n a = factorial' (n-1) (n*a)\n</code></pre>\n"}, {'answer_id': 38781, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 2, 'selected': False, 'text': '<p>Agda 2: Functional, dependently typed.</p>\n\n<pre><code>data Nat = zero | suc (m::Nat)\n\nadd (m::Nat) (n::Nat) :: Nat\n = case m of\n     (zero ) -&gt; n\n     (suc p) -&gt; suc (add p n)\n\nmul (m::Nat) (n::Nat)::Nat\n   = case m of\n      (zero ) -&gt; zero\n      (suc p) -&gt; add n (mul p n)\n\nfactorial (n::Nat)::Nat \n = case n of\n    (zero ) -&gt; suc zero\n    (suc p) -&gt; mul n (factorial p)\n</code></pre>\n'}, {'answer_id': 38935, 'author': 'vzczc', 'author_id': 224, 'author_profile': 'https://Stackoverflow.com/users/224', 'pm_score': 5, 'selected': False, 'text': '<p>C# Lookup:</p>\n\n<p>Nothing to calculate really, just look it up. To extend it,add another 8 numbers to the table and 64 bit integers are at at their limit. Beyond that, a BigNum class is called for. </p>\n\n<pre><code>public static int Factorial(int f)\n{ \n    if (f&lt;0 || f&gt;12)\n    {\n        throw new ArgumentException("Out of range for integer factorial");\n    }\n    int [] fact={1,1,2,6,24,120,720,5040,40320,362880,3628800,\n                 39916800,479001600};\n    return fact[f];\n}\n</code></pre>\n'}, {'answer_id': 41071, 'author': 'Andres', 'author_id': 1815, 'author_profile': 'https://Stackoverflow.com/users/1815', 'pm_score': 5, 'selected': False, 'text': '<h1>Whitespace</h1>\n\n<pre>\n&#32;&#32;&#32;&#09;.\n&#32;.\n&#32;&#09;.\n&#09;&#09;.\n&#32;&#32;&#09;.\n&#32;&#32;&#32;&#09;.\n&#09;&#09;&#09;&#32;.\n&#32;.\n&#09;&#32;&#09;&#32;.\n&#09;&#32;&#32;.\n&#32;&#32;&#32;&#09;.\n&#32;.\n&#32;&#32;.\n&#32;&#09;&#09;&#09;&#32;.\n&#09;&#09;&#32;&#32;&#09;&#09;&#09;&#32;.\n&#32;.\n&#09;.\n.\n&#32;&#32;&#09;&#32;.\n&#32;.\n.\n&#09;.\n&#32;&#09;.\n.\n.\n.\n</pre>\n\n<p>It was hard to get it to show here properly, but now I tried copying it from the preview and it works. You need to input the number and press enter.</p>\n'}, {'answer_id': 43858, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 2, 'selected': False, 'text': '<h1>Delphi</h1>\n<pre><code>facts: array[2..12] of integer;\n\nfunction TForm1.calculate(f: integer): integer;\nbegin\n    if f = 1 then\n      Result := f\n    else if f &gt; High(facts) then\n      Result := High(Integer)\n    else if (facts[f] &gt; 0) then\n      Result := facts[f]\n    else begin\n      facts[f] := f * Calculate(f-1);\n      Result := facts[f];\n    end;\nend;\n\ninitialize\n\n  for i := Low(facts) to High(facts) do\n    facts[i] := 0;\n</code></pre>\n<p>After the first time a factorial higher or equal to the desired value has been calculated, this algorithm just returns the factorial in constant time O(1).</p>\n<p>It takes in account that int32 only can hold up to 12!</p>\n'}, {'answer_id': 49300, 'author': 'Jared Updike', 'author_id': 2543, 'author_profile': 'https://Stackoverflow.com/users/2543', 'pm_score': 5, 'selected': False, 'text': '<h1><a href="http://homepages.cwi.nl/~tromp/cl/lazy-k.html" rel="nofollow noreferrer">Lazy</a> <a href="http://esoteric.sange.fi/essie2/download/" rel="nofollow noreferrer" title="download it">K</a></h1>\n\n<p>Your pure functional programming nightmares come true!</p>\n\n<p>The only <a href="http://en.wikipedia.org/wiki/Esoteric_programming_language" rel="nofollow noreferrer">Esoteric Turing-complete Programming Language</a> that has:</p>\n\n<ul>\n<li>A purely functional foundation, core, and libraries---in fact, here\'s the complete API: <a href="http://en.wikipedia.org/wiki/SKI_combinator_calculus" rel="nofollow noreferrer">S K I</a></li>\n<li>No <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="nofollow noreferrer">lambdas</a> even!</li>\n<li>No <a href="http://en.wikipedia.org/wiki/Church_encoding#Church_numerals" rel="nofollow noreferrer">numbers</a> or lists needed or allowed</li>\n<li>No explicit recursion but yet, <a href="http://mvanier.livejournal.com/2897.html" rel="nofollow noreferrer" title="Mike Vanier - Y Combinator (Slight Return">allows recursion</a></li>\n<li>A simple <a href="http://mitpress.mit.edu/sicp/full-text/sicp/book/node71.html" rel="nofollow noreferrer">infinite lazy stream</a>-based I/O mechanism</li>\n</ul>\n\n<p>Here\'s the Factorial code in all its parenthetical glory:</p>\n\n<pre><code>K(SII(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(K(S(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))))))))K))))))(S(K(S(K(S(SI(K(S(K(S(SI(K(S(K(S(S(KS)K)I))\n (S(S(KS)K)(SII(S(S(KS)K)I))(S(S(KS)K))(S(SII)I(S(S(KS)K)I))))))))K)))))))\n (S(S(KS)K)(K(S(S(KS)K)))))))))(K(S(K(S(S(KS)K)))K))))(SII))II)\n</code></pre>\n\n<p>Features:</p>\n\n<ul>\n<li>No subtraction or conditionals</li>\n<li>Prints all factorials (if you wait long enough)</li>\n<li>Uses a second layer of Church numerals to convert the Nth factorial to N! asterisks followed by a newline</li>\n<li>Uses the <a href="http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator" rel="nofollow noreferrer">Y combinator</a> for recursion</li>\n</ul>\n\n<p>In case you are interested in trying to understand it, here is the Scheme source code to run through the Lazier compiler:</p>\n\n<pre><code>(lazy-def \'(fac input)\n   \'((Y (lambda (f n a) ((lambda (b) ((cons 10) ((b (cons 42)) (f (1+ n) b))))\n       (* a n)))) 1 1))\n</code></pre>\n\n<p>(for suitable definitions of Y, cons, 1, 10, 42, 1+, and *).</p>\n\n<p>EDIT:</p>\n\n<h1>Lazy K Factorial in Decimal</h1>\n\n<p>(<a href="http://www.updike.org/hazy/facdec.lazy" rel="nofollow noreferrer">10KB of gibberish</a> or else I would paste it). For example, at the Unix prompt:</p>\n\n<pre>\n    $ echo "4" | ./lazy facdec.lazy\n    24\n    $ echo "5" | ./lazy facdec.lazy\n    120\n</pre>\n\n<p>Rather slow for numbers above, say, 5.</p>\n\n<p>The code is sort of bloated because we have to include <a href="http://www.updike.org/hazy/factorialDecimal.hazy" rel="nofollow noreferrer">library code for all of our own primitives</a> (code written in <a href="http://www.updike.org/hazy/" rel="nofollow noreferrer">Hazy</a>, a lambda calculus interpreter and LC-to-Lazy K compiler written in Haskell).</p>\n'}, {'answer_id': 49312, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 4, 'selected': False, 'text': '<h1>C#: LINQ</h1>\n\n<pre><code>    public static int factorial(int n)\n    {\n        return (Enumerable.Range(1, n).Aggregate(1, (previous, value) =&gt; previous * value));\n    }\n</code></pre>\n'}, {'answer_id': 49444, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 3, 'selected': False, 'text': '<p>The problem with most of the above is that they will run out of precision at about 25! (12! with 32 bit ints) or just overflow. Here\'s a c# implementation to break through these limits!</p>\n\n<pre><code>class Number\n{\n  public Number ()\n  {\n    m_number = "0";\n  }\n\n  public Number (string value)\n  {\n    m_number = value;\n  }\n\n  public int this [int column]\n  {\n    get\n    {\n      return column &lt; m_number.Length ? m_number [m_number.Length - column - 1] - \'0\' : 0;\n    }\n  }\n\n  public static implicit operator Number (string rhs)\n  {\n    return new Number (rhs);\n  }\n\n  public static bool operator == (Number lhs, Number rhs)\n  {\n    return lhs.m_number == rhs.m_number;\n  }\n\n  public static bool operator != (Number lhs, Number rhs)\n  {\n    return lhs.m_number != rhs.m_number;\n  }\n\n  public override bool Equals (object obj)\n  {\n     return this == (Number) obj;\n  }\n\n  public override int GetHashCode ()\n  {\n    return m_number.GetHashCode ();\n  }\n\n  public static Number operator + (Number lhs, Number rhs)\n  {\n    StringBuilder\n      result = new StringBuilder (new string (\'0\', lhs.m_number.Length + rhs.m_number.Length));\n\n    int\n      carry = 0;\n\n    for (int i = 0 ; i &lt; result.Length ; ++i)\n    {\n      int\n        sum = carry + lhs [i] + rhs [i],\n        units = sum % 10;\n\n      carry = sum / 10;\n\n      result [result.Length - i - 1] = (char) (\'0\' + units);\n    }\n\n    return TrimLeadingZeros (result);\n  }\n\n  public static Number operator * (Number lhs, Number rhs)\n  {\n    StringBuilder\n      result = new StringBuilder (new string (\'0\', lhs.m_number.Length + rhs.m_number.Length));\n\n    for (int multiplier_index = rhs.m_number.Length - 1 ; multiplier_index &gt;= 0 ; --multiplier_index)\n    {\n      int\n        multiplier = rhs.m_number [multiplier_index] - \'0\',\n        column = result.Length - rhs.m_number.Length + multiplier_index;\n\n      for (int i = lhs.m_number.Length - 1 ; i &gt;= 0 ; --i, --column)\n      {\n        int\n          product = (lhs.m_number [i] - \'0\') * multiplier,\n          units = product % 10,\n          tens = product / 10,\n          hundreds = 0,\n          unit_sum = result [column] - \'0\' + units;\n\n        if (unit_sum &gt; 9)\n        {\n          unit_sum -= 10;\n          ++tens;\n        }\n\n        result [column] = (char) (\'0\' + unit_sum);\n\n        int\n          tens_sum = result [column - 1] - \'0\' + tens;\n\n        if (tens_sum &gt; 9)\n        {\n          tens_sum -= 10;\n          ++hundreds;\n        }\n\n        result [column - 1] = (char) (\'0\' + tens_sum);\n\n        if (hundreds &gt; 0)\n        {\n          int\n            hundreds_sum = result [column - 2] - \'0\' + hundreds;\n\n          result [column - 2] = (char) (\'0\' + hundreds_sum);\n        }\n      }\n    }\n\n    return TrimLeadingZeros (result);\n  }\n\n  public override string ToString ()\n  {\n    return m_number;\n  }\n\n  static string TrimLeadingZeros (StringBuilder number)\n  {\n    while (number [0] == \'0\' &amp;&amp; number.Length &gt; 1)\n    {\n      number.Remove (0, 1);\n    }\n\n    return number.ToString ();\n  }\n\n  string\n    m_number;\n}\n\nstatic void Main (string [] args)\n{\n  Number\n    a = new Number ("1"),\n    b = new Number (args [0]),\n    one = new Number ("1");\n\n  for (Number c = new Number ("1") ; c != b ; )\n  {\n    c = c + one;\n    a = a * c;\n  }\n\n  Console.WriteLine (string.Format ("{0}! = {1}", new object [] { b, a }));\n}\n</code></pre>\n\n<p>FWIW: 10000! is over 35500 character long.</p>\n\n<p>Skizz</p>\n'}, {'answer_id': 51952, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 4, 'selected': False, 'text': '<h1>Python: Functional, One-liner</h1>\n\n<pre><code>factorial = lambda n: reduce(lambda x,y: x*y, range(1, n+1), 1)\n</code></pre>\n\n<p>NOTE:</p>\n\n<ul>\n<li>It supports big integers. Example:</li>\n</ul>\n\n<hr>\n\n<pre><code>print factorial(100)\n93326215443944152681699238856266700490715968264381621468592963895217599993229915\\\n608941463976156518286253697920827223758251185210916864000000000000000000000000\n</code></pre>\n\n<hr>\n\n<ul>\n<li>It does not work for <em>n &lt; 0</em>.</li>\n</ul>\n'}, {'answer_id': 51975, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 6, 'selected': False, 'text': '<p>This is one of the faster algorithms, up to <a href="http://www.google.com/search?q=170!" rel="nofollow noreferrer">170!</a>.  It <a href="http://www.google.com/search?q=171!" rel="nofollow noreferrer">fails</a> inexplicably beyond 170!, and it\'s relatively slow for small factorials, but for factorials between <a href="http://www.google.com/search?q=80!" rel="nofollow noreferrer">80</a> and <a href="http://www.google.com/search?q=170!" rel="nofollow noreferrer">170</a> it\'s blazingly fast compared to many algorithms.</p>\n<pre><code>curl http://www.google.com/search?q=170!\n</code></pre>\n<p>There\'s also an online interface, <a href="http://www.google.com/search?q=42!" rel="nofollow noreferrer">try it out now!</a></p>\n<p>Let me know if you find a bug, or faster implementation for large factorials.</p>\n<hr />\n<h3>EDIT:</h3>\n<p>This algorithm is slightly slower, but gives results beyond 170:</p>\n<pre><code>curl http://www58.wolframalpha.com/input/?i=171!\n</code></pre>\n<p>It also simplifies them into various other representations.</p>\n'}, {'answer_id': 52946, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 1, 'selected': False, 'text': '<h1>Python, C/C++ (weave): Multi-Language, Procedural</h1>\n\n<p>Four implementations:</p>\n\n<ul>\n<li>[weave]</li>\n<li>[python]</li>\n<li>[psyco]</li>\n<li>[list]</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>#!/usr/bin/env python\n""" weave_factorial.py\n\n"""\n# [weave] factorial() as extension module in C++\nfrom scipy.weave import ext_tools\n\ndef build_factorial_ext():\n    func = ext_tools.ext_function(\n        \'factorial\', \n        r"""\n        unsigned long long i = 1;\n        for ( ; n &gt; 1; --n)\n          i *= n;\n\n        PyObject *o = PyLong_FromUnsignedLongLong(i);\n        return_val = o;\n        Py_XDECREF(o); \n        """,  \n        [\'n\'], \n        {\'n\': 1}, # effective type declaration\n        {})\n    mod = ext_tools.ext_module(\'factorial_ext\')\n    mod.add_function(func)\n    mod.compile()\n\ntry: from factorial_ext import factorial as factorial_weave\nexcept ImportError:\n    build_factorial_ext()\n    from factorial_ext import factorial as factorial_weave\n\n\n# [python] pure python procedural factorial()\ndef factorial_python(n):\n    i = 1\n    while n &gt; 1:\n        i *= n\n        n -= 1\n    return i\n\n\n# [psyco] factorial() psyco-optimized\ntry:\n    import psyco\n    factorial_psyco = psyco.proxy(factorial_python)\nexcept ImportError:\n    pass\n\n\n# [list] list-lookup factorial()\nfactorials = map(factorial_python, range(21))   \nfactorial_list = lambda n: factorials[n]\n</code></pre>\n\n<hr>\n\n<p>Measure relative performance:</p>\n\n<pre><code>$ python -mtimeit \\\n         -s "from weave_factorial import factorial_$label as f" "f($n)"\n</code></pre>\n\n<ol>\n<li><p>n = 12</p>\n\n<ul>\n<li>[weave] 0.70 &micro;sec (<strong>2</strong>)</li>\n<li>[python] 3.8 &micro;sec (<strong>9</strong>)</li>\n<li>[psyco]  1.2 &micro;sec (<strong>3</strong>)</li>\n<li>[list]  0.43 &micro;sec (<strong>1</strong>)</li>\n</ul></li>\n<li><p>n = 20 </p>\n\n<ul>\n<li>[weave] 0.85 &micro;sec (<strong>2</strong>)</li>\n<li>[python] 9.2 &micro;sec (<strong>21</strong>)</li>\n<li>[psyco]  4.3 &micro;sec (<strong>10</strong>)</li>\n<li>[list]  0.43 &micro;sec (<strong>1</strong>)</li>\n</ul></li>\n</ol>\n\n<p><em>&micro;sec</em> stands for microseconds.</p>\n'}, {'answer_id': 53810, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 3, 'selected': False, 'text': '<h1>Lambda Calculus</h1>\n\n<p>Input and output are Church numerals (i.e. natural number <code>k</code> is <code>\\f n. f^k n</code>; so <code>3 = \\f n. f (f (f n)))</code></p>\n\n<pre><code>(\\x. x x) (\\y f. f (y y f)) (\\y n. n (\\x y z. z) (\\x y. x) (\\f n. f n) (\\f. n (y (\\f m. n (\\g h. h (g f)) (\\x. m) (\\x. x)) f)))\n</code></pre>\n'}, {'answer_id': 58361, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<h1>Ruby: Iterative</h1>\n\n<pre><code>def factorial(n)\n  (1 .. n).inject{|a, b| a*b}\nend\n</code></pre>\n\n<h1>Ruby: Recursive</h1>\n\n<pre><code>def factorial(n)\n  n == 1 ? 1 : n * factorial(n-1)\nend\n</code></pre>\n'}, {'answer_id': 58368, 'author': 'Serafina Brocious', 'author_id': 4977, 'author_profile': 'https://Stackoverflow.com/users/4977', 'pm_score': 2, 'selected': False, 'text': '<p>Nemerle: Functional</p>\n\n<pre><code>def fact(n) {\n    | 0 =&gt; 1\n    | x =&gt; x * fact(x-1)\n}\n</code></pre>\n'}, {'answer_id': 58433, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 2, 'selected': False, 'text': '<pre><code>#Language: T-SQL\n#Style: Recursive, divide and conquer\n</code></pre>\n\n<p>Just for fun - in T-SQL using a divide and conquer recursive method. Yes, recursive - in SQL without stack overflow.</p>\n\n<pre><code>create function factorial(@b int=1, @e int) returns float as begin\n  return case when @b&gt;=@e then @e else \n      convert(float,dbo.factorial(@b,convert(int,@b+(@e-@b)/2)))\n    * convert(float,dbo.factorial(convert(int,@b+1+(@e-@b)/2),@e)) end\nend\n</code></pre>\n\n<p>call it like this:</p>\n\n<pre><code>print dbo.factorial(1,170) -- the 1 being the starting number\n</code></pre>\n'}, {'answer_id': 58594, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 2, 'selected': False, 'text': "<pre><code>#Language: T-SQL\n#Style: Big Numbers\n</code></pre>\n\n<p>Here's another T-SQL solution -- supports big numbers in a most Rube Goldbergian manner. Lots of set-based ops. Tried to keep it uniquely SQL. Horrible performance (400! took 33 seconds on a Dell Latitude D830)</p>\n\n<pre><code>create function bigfact(@x varchar(max)) returns varchar(max) as begin\n  declare @c int\n  declare @n table(n int,e int)\n  declare @f table(n int,e int)\n\n  set @c=0\n  while @c&lt;len(@x) begin\n    set @c=@c+1\n    insert @n(n,e) values(convert(int,substring(@x,@c,1)),len(@x)-@c)\n  end\n\n  -- our current factorial\n  insert @f(n,e) select 1,0\n\n  while 1=1 begin\n    declare @p table(n int,e int)\n    delete @p\n    -- product\n    insert @p(n,e) select sum(f.n*n.n), f.e+n.e from @f f cross join @n n group by f.e+n.e\n\n    -- normalize\n    while 1=1 begin\n      delete @f\n      insert @f(n,e) select sum(n),e from (\n        select (n % 10) as n,e from @p union all \n        select (n/10) % 10,e+1 from @p union all \n        select (n/100) %10,e+2 from @p union all \n        select (n/1000)%10,e+3 from @p union all \n        select (n/10000) % 10,e+4 from @p union all \n        select (n/100000)% 10,e+5 from @p union all \n        select (n/1000000)%10,e+6 from @p union all \n        select (n/10000000) % 10,e+7 from @p union all \n        select (n/100000000)% 10,e+8 from @p union all \n        select (n/1000000000)%10,e+9 from @p\n      ) f group by e having sum(n)&gt;0\n\n      set @c=0\n      select @c=count(*) from @f where n&gt;9\n      if @c=0 break\n      delete @p\n      insert @p(n,e) select n,e from @f\n    end\n\n    -- decrement\n    update @n set n=n-1 where e=0\n\n    -- normalize\n    while 1=1 begin\n      declare @e table(e int)\n      delete @e\n      insert @e(e) select e from @n where n&lt;0\n      if @@rowcount=0 break\n\n      update @n set n=n+10 where e in (select e from @e)\n      update @n set n=n-1 where e in (select e+1 from @e)\n    end  \n\n    set @c=0\n    select @c=count(*) from @n where n&gt;0\n    if @c=0 break\n  end\n\n  select @c=max(e) from @f\n  set @x=''\n  declare @l varchar(max)\n  while @c&gt;=0 begin\n    set @l='0'\n    select @l=convert(varchar(max),n) from @f where e=@c\n    set @x=@x+@l\n    set @c=@c-1\n  end\n  return @x\nend\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>print dbo.bigfact('69')\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000\n</code></pre>\n"}, {'answer_id': 65432, 'author': 'user9282', 'author_id': 9282, 'author_profile': 'https://Stackoverflow.com/users/9282', 'pm_score': 5, 'selected': False, 'text': '<p>I find the following implementations just hilarious:</p>\n\n<p><a href="http://www.willamette.edu/~fruehr/haskell/evolution.html" rel="nofollow noreferrer">The Evolution of a Haskell Programmer</a></p>\n\n<p><a href="http://dis.4chan.org/read/prog/1180084983/" rel="nofollow noreferrer">Evolution of a Python programmer</a></p>\n\n<p>Enjoy!</p>\n'}, {'answer_id': 67805, 'author': 'AShelly', 'author_id': 10396, 'author_profile': 'https://Stackoverflow.com/users/10396', 'pm_score': 3, 'selected': False, 'text': '<h1>ruby recursive</h1>\n<pre><code>(factorial=Hash.new{|h,k|k*h[k-1]})[1]=1\n    \n</code></pre>\n<p>usage:</p>\n<pre><code>factorial[5]\n =&gt; 120\n</code></pre>\n'}, {'answer_id': 67979, 'author': 'Paul Reiners', 'author_id': 7648, 'author_profile': 'https://Stackoverflow.com/users/7648', 'pm_score': 2, 'selected': False, 'text': '<h1>Language Name: <a href="http://chuck.cs.princeton.edu/" rel="nofollow noreferrer">ChucK</a></h1>\n\n<pre><code>Moog moog =&gt; dac;\n4.0 =&gt; moog.gain;\n\nfor (0 =&gt; int i; i &lt; 8; i++) {\n    &lt;&lt;&lt; factorial(i) &gt;&gt;&gt;;\n}\n\nfun int factorial(int n) {\n    1 =&gt; int result;\n    if (n != 0) {\n        n * factorial(n - 1) =&gt; result;\n    }\n\n    Std.mtof(result % 128) =&gt; moog.freq;\n    0.25::second =&gt; now;\n\n    return result;\n}\n</code></pre>\n\n<p>And it sounds like <a href="http://www.automatous-monk.com/mp3s/misc/Factorial.mp3" rel="nofollow noreferrer">this</a>.  Not terribly interesting, but, hey, it\'s just a factorial function!</p>\n'}, {'answer_id': 71849, 'author': 'TonJ', 'author_id': 11537, 'author_profile': 'https://Stackoverflow.com/users/11537', 'pm_score': 4, 'selected': False, 'text': '<h1>Brainf*ck</h1>\n\n<pre><code>+++++\n&gt;+&lt;[[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;+&gt;&gt;]&lt;&lt;&lt;&lt;&gt;[-&gt;&gt;+&lt;&lt;]&lt;&gt;&gt;&gt;[-&lt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;[-&lt;&lt;+&lt;+&gt;&gt;&gt;]&lt;]&lt;[-]&gt;&lt;&lt;&lt;-]\n</code></pre>\n\n<p>Written by Michael Reitzenstein.</p>\n'}, {'answer_id': 81669, 'author': 'Christian Davén', 'author_id': 12534, 'author_profile': 'https://Stackoverflow.com/users/12534', 'pm_score': 4, 'selected': False, 'text': '<h1><a href="http://en.wikipedia.org/wiki/APL_(programming_language)" rel="nofollow noreferrer">APL</a> (oddball/one-liner):</h1>\n\n<pre><code>×/⍳X\n</code></pre>\n\n<ol>\n<li>⍳X expands X into an array of the integers 1..X</li>\n<li>×/ multiplies every element in the array</li>\n</ol>\n\n<p>Or with the built-in operator:</p>\n\n<pre><code>!X\n</code></pre>\n\n<p>Source: <a href="http://www.webber-labs.com/mpl/lectures/ppt-slides/01.ppt" rel="nofollow noreferrer">http://www.webber-labs.com/mpl/lectures/ppt-slides/01.ppt</a></p>\n'}, {'answer_id': 82369, 'author': 'J.D. Fitz.Gerald', 'author_id': 11542, 'author_profile': 'https://Stackoverflow.com/users/11542', 'pm_score': 3, 'selected': False, 'text': "<h1>Bash: Recursive</h1>\n<p>In bash and recursive, but with the added advantage that it deals with each iteration in a new process. The max it can calculate is !20 before overflowing, but you can still run it for big numbers if you don't care about the answer and want your system to fall over ;)</p>\n<pre><code>#!/bin/bash\necho $(($1 * `( [[ $1 -gt 1 ]] && ./$0 $(($1 - 1)) ) || echo 1`));\n</code></pre>\n"}, {'answer_id': 90589, 'author': 'user11318', 'author_id': 11318, 'author_profile': 'https://Stackoverflow.com/users/11318', 'pm_score': 1, 'selected': False, 'text': '<p>Here is an interesting Ruby version.  On my laptop it will find 30000! in under a second.  (It takes longer for Ruby to format it for printing than to calculate it.)  This is significantly faster than the naive solution of just multiplying the numbers in order.</p>\n\n<pre><code>def factorial (n)\n  return multiply_range(1, n)\nend\n\ndef multiply_range(n, m)\n  if (m &lt; n)\n    return 1\n  elsif (n == m)\n    return m\n  else\n    i = (n + m) / 2\n    return multiply_range(n, i) * multiply_range(i+1, m)\n  end\nend\n</code></pre>\n'}, {'answer_id': 90659, 'author': 'Martin York', 'author_id': 14065, 'author_profile': 'https://Stackoverflow.com/users/14065', 'pm_score': 2, 'selected': False, 'text': '<p>Simple solutions are the best:</p>\n\n<pre><code>#include &lt;stdexcept&gt;;\n\nlong fact(long f)\n{\n    static long fact [] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 1932053504, 1278945280, 2004310016, 2004189184 };\n    static long max     = sizeof(fact)/sizeof(long);\n\n    if ((f &lt; 0) || (f &gt;= max))\n    {   throw std::range_error("Factorial Range Error");\n    }\n\n    return fact[f];\n}\n</code></pre>\n'}, {'answer_id': 90728, 'author': 'Matthias Benkard', 'author_id': 15517, 'author_profile': 'https://Stackoverflow.com/users/15517', 'pm_score': 2, 'selected': False, 'text': '<h1>Common Lisp: Lisp as God intended it to be used (that is, with LOOP)</h1>\n\n<pre><code>(defun fact (n)\n  (loop for i from 1 to n\n        for acc = 1 then (* acc i)\n        finally (return acc)))\n</code></pre>\n\n<p>Now, if someone can come up with a version based on FORMAT...</p>\n'}, {'answer_id': 90911, 'author': 'Matthias Benkard', 'author_id': 15517, 'author_profile': 'https://Stackoverflow.com/users/15517', 'pm_score': 2, 'selected': False, 'text': '<h1>Common Lisp: FORMAT (obfuscated)</h1>\n\n<p>Okay, so I\'ll give it a try myself.</p>\n\n<pre><code>(defun format-fact (stream arg colonp atsignp &amp;rest args)\n  (destructuring-bind (n acc) arg\n    (format stream\n            "~[~A~:;~*~/format-fact/~]"\n            (1- n)\n            acc\n            (list (1- n) (* acc n)))))\n\n(defun fact (n)\n  (parse-integer (format nil "~/format-fact/" (list n 1))))\n</code></pre>\n\n<p>There has to be a nicer, even more obscure FORMAT-based implementation.  This one is pretty straight-forward and boring, simply using FORMAT as an IF replacement.  Obviously, I\'m not a FORMAT expert.</p>\n'}, {'answer_id': 91001, 'author': 'Hugh Allen', 'author_id': 15069, 'author_profile': 'https://Stackoverflow.com/users/15069', 'pm_score': 4, 'selected': False, 'text': "<h2>Recursively in Inform 7</h2>\n<p>(it reminds you of COBOL because it's for writing text adventures; proportional font is deliberate):</p>\n<blockquote>\n<p>To decide what number is the factorial of (n - a number):<br>\n\xa0\xa0\xa0\xa0if n is zero, decide on one;<br>\n\xa0\xa0\xa0\xa0otherwise decide on the factorial of (n minus one) times n.</p>\n</blockquote>\n<p>If you want to actually call this function (&quot;phrase&quot;) from a game you need to define an action and grammar rule:</p>\n<blockquote>\n<p>&quot;The factorial game&quot; [this must be the first line of the source]</p>\n<p>There is a room. [there has to be at least one!]</p>\n<p>Factorialing is an action applying to a number.</p>\n<p>Understand &quot;factorial [a number]&quot; as factorialing.</p>\n<p>Carry out factorialing:<br>\n\xa0\xa0\xa0\xa0Let n be the factorial of the number understood;<br>\n\xa0\xa0\xa0\xa0Say &quot;It's [n]&quot;.</p>\n</blockquote>\n"}, {'answer_id': 91039, 'author': 'Calum', 'author_id': 8434, 'author_profile': 'https://Stackoverflow.com/users/8434', 'pm_score': 1, 'selected': False, 'text': '<h1>Scala: Recursive</h1>\n\n<ul>\n<li>Should compile to being tail recursive. Should!</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>def factorial( value: BigInt ): BigInt = value match {\n  case 0 =&gt; 1\n  case _ =&gt; value * factorial( value - 1 )\n}\n</code></pre>\n'}, {'answer_id': 91175, 'author': 'Dynite', 'author_id': 16177, 'author_profile': 'https://Stackoverflow.com/users/16177', 'pm_score': 1, 'selected': False, 'text': '<p>Occam-pi</p>\n\n<pre><code>PROC subprocess(MOBILE CHAN INT parent.out!,parent.in?)\nINT value:\n  SEQ\n    parent.in ? value\n      IF \n        value = 1\n          SEQ\n            parent.out ! value\n        OTHERWISE\n          INITIAL MOBILE CHAN INT child.in IS MOBILE CHAN INT:\n          INITIAL MOBILE CHAN INT child.out IS MOBILE CHAN INT:\n          FORKING\n            INT newvalue:\n            SEQ\n              FORK subprocess(child.in!,child.out?)\n              child.out ! (value-1)\n              child.in ? newvalue\n              parent.out ! (newalue*value)\n:\n\nPROC main(CHAN BYTE in?,src!,kyb?)\nINITIAL INT value IS 0:\nINITIAL MOBILE CHAN INT child.out is MOBILE CHAN INT\nINITIAL MOBILE CHAN INT child.in is MOBILE CHAN INT\nSEQ \n  WHILE TRUE\n    SEQ\n      subprocess(child.in!,child.out?)\n      child.out ! value\n      child.in ? value\n      src ! value:\n      value := value + 1\n:\n</code></pre>\n'}, {'answer_id': 100199, 'author': 'Hugh Allen', 'author_id': 15069, 'author_profile': 'https://Stackoverflow.com/users/15069', 'pm_score': 2, 'selected': False, 'text': "<h1>Icon</h1>\n\n<h2>Recursive function</h2>\n\n<pre><code>procedure factorial(n)\n  return (0&lt;n) * factorial(n-1) | 1\nend\n</code></pre>\n\n<p>I've cheated a bit allowing negatives to return 1. If you want it to fail given a negative argument it's slightly less concise:</p>\n\n<pre><code>  return (0&lt;n) * factorial(n-1) | (n=0 &amp; 1)\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>write(factorial(3))\nwrite(factorial(-1))\nwrite(factorial(20))\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>6\n2432902008176640000\n</code></pre>\n\n<h2>Iterative generator</h2>\n\n<pre><code>procedure factorials()\n  local f,n\n  f := 1; n := 0\n  repeat suspend f *:= (n +:= 1)\nend\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>every write(factorials() \\ 5)\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>1\n2\n6\n24\n120\n</code></pre>\n\n<p>To understand this: evaluation is goal-directed and backtracks on failure. There is no boolean type, and binary operators which would return a boolean in other languages, either fail or return their second argument - with the exception of |, which in a single-value context returns its first argument if it succeeds, otherwise tries its second argument. (in a multiple-value context it returns its first argument <em>then</em> its second argument)</p>\n\n<p><code>suspend</code> is like <code>yield</code> in other languages, except that a generator is not explicitly called multiple times to return its results. Instead,\n<code>every</code> asks its argument for all values but doesn't return anything by default; it's useful with side-effects (in this case I/O).</p>\n\n<p><code>\\</code> limits the number of values returned by a generator, which in the case of <code>factorials</code> would be infinite.</p>\n"}, {'answer_id': 106580, 'author': 'Jiří Pospíšil', 'author_id': 19093, 'author_profile': 'https://Stackoverflow.com/users/19093', 'pm_score': 0, 'selected': False, 'text': '<p><strong>FoxPro:</strong></p>\n\n<pre><code>function factorial\n    parameters n\nreturn iif( n&gt;0, n*factorial(n-1), 1)\n</code></pre>\n'}, {'answer_id': 106621, 'author': 'mbac32768', 'author_id': 18446, 'author_profile': 'https://Stackoverflow.com/users/18446', 'pm_score': 1, 'selected': False, 'text': "<h2>OCaml</h2>\n\n<p>Lest anyone believe OCaml and oddball go hand-in-hand, I thought I would provide a sane implementation of factorial.</p>\n\n<pre><code># let rec factorial n =\n    if n=0 then 1 else n * factorial(n - 1);;\n</code></pre>\n\n<p>I don't think I made my case very well...</p>\n"}, {'answer_id': 114277, 'author': 'dogbane', 'author_id': 7412, 'author_profile': 'https://Stackoverflow.com/users/7412', 'pm_score': 2, 'selected': False, 'text': '<p><strong>AWK</strong></p>\n\n<pre><code>#!/usr/bin/awk -f\n{\n    result=1;\n    for(i=$1;i&gt;0;i--){\n        result=result*i;\n    }\n    print result;\n}\n</code></pre>\n'}, {'answer_id': 114930, 'author': 'Einar', 'author_id': 20445, 'author_profile': 'https://Stackoverflow.com/users/20445', 'pm_score': 1, 'selected': False, 'text': '<p>Genuinely functional Java:</p>\n\n<pre><code>public final class Factorial {\n\n  public static void main(String[] args) {\n    final int n = Integer.valueOf(args[0]);\n    System.out.println("Factorial of " + n + " is " + create(n).apply());\n  }\n\n  private static Function create(final int n) {\n    return n == 0 ? new ZeroFactorialFunction() : new NFactorialFunction(n);\n  }\n\n  interface Function {\n    int apply();\n  }\n\n  private static class NFactorialFunction implements Function {\n    private final int n;\n    public NFactorialFunction(final int n) {\n      this.n = n;\n    }\n    @Override\n    public int apply() {\n      return n * Factorial.create(n - 1).apply();\n    }\n  }\n\n  private static class ZeroFactorialFunction implements Function {\n    @Override\n    public int apply() {\n      return 1;\n    }\n  }\n\n}\n</code></pre>\n'}, {'answer_id': 115633, 'author': 'Alnitak', 'author_id': 6782, 'author_profile': 'https://Stackoverflow.com/users/6782', 'pm_score': 4, 'selected': False, 'text': '<h1>Erlang: tail recursive</h1>\n\n<pre><code>fac(0) -&gt; 1;\nfac(N) when N &gt; 0 -&gt; fac(N, 1).\n\nfac(1, R) -&gt; R;\nfac(N, R) -&gt; fac(N - 1, R * N).\n</code></pre>\n'}, {'answer_id': 153790, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 2, 'selected': False, 'text': '<pre><code>#Language: T-SQL, C#\n#Style: Custom Aggregate\n</code></pre>\n\n<p>Another crazy way would be to create a custom aggregate and apply it over a temporary table of the integers 1..n.</p>\n\n<pre><code>/* ProductAggregate.cs */\nusing System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\n[Serializable]\n[SqlUserDefinedAggregate(Format.Native)]\npublic struct product {\n  private SqlDouble accum;\n  public void Init() { accum = 1; }\n  public void Accumulate(SqlDouble value) { accum *= value; }\n  public void Merge(product value) { Accumulate(value.Terminate()); }\n  public SqlDouble Terminate() { return accum; }\n}\n</code></pre>\n\n<p>add this to sql</p>\n\n<pre><code>create assembly ProductAggregate from \'ProductAggregate.dll\' with permission_set=safe -- mod path to point to actual dll location on disk.\n\ncreate aggregate product(@a float) returns float external name ProductAggregate.product\n</code></pre>\n\n<p>create the table (there should be a built-in way to do this in SQL -- hmm. a <a href="https://stackoverflow.com/questions/58429/sql-set-based-range">question</a> for SO?)</p>\n\n<pre><code>select 1 as n into #n union select 2 union select 3 union select 4 union select 5\n</code></pre>\n\n<p>then finally</p>\n\n<pre><code>select dbo.product(n) from #n\n</code></pre>\n'}, {'answer_id': 201631, 'author': 'Chris S', 'author_id': 21574, 'author_profile': 'https://Stackoverflow.com/users/21574', 'pm_score': 3, 'selected': False, 'text': '<p>The code below is tongue in cheek, however when you consider that the return value is limited to n &lt; 34 for uint32, &lt;65 uint64 before we run out of space for the return value with a uint, <strong>hard coding 33 values isn\'t that crazy</strong> :)</p>\n\n<pre><code>public static int Factorial(int n)\n{\n    switch (n)\n    {\n        case 1:\n            return 1;\n        case 2:\n            return 2;\n        case 3:\n            return 6;\n        case 4:\n            return 24;\n        default:\n            throw new Exception("Sorry, I can only count to 4");\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 201662, 'author': 'milot', 'author_id': 22637, 'author_profile': 'https://Stackoverflow.com/users/22637', 'pm_score': 1, 'selected': False, 'text': '<p><strong>C# factorial using recursion in a single line</strong></p>\n\n<pre><code>private static int factorial(int n){ if (n == 0)return 1;else return n * factorial(n - 1); }\n</code></pre>\n'}, {'answer_id': 215337, 'author': 'nonowarn', 'author_id': 28720, 'author_profile': 'https://Stackoverflow.com/users/28720', 'pm_score': 4, 'selected': False, 'text': '<h1>Perl6</h1>\n\n<pre><code>sub factorial ($n) { [*] 1..$n }\n</code></pre>\n\n<p>I hardly know about Perl6. But I guess this <code>[*]</code> operator is same as Haskell\'s <code>product</code>.</p>\n\n<p>This code runs on <a href="http://pugscode.org/" rel="nofollow noreferrer">Pugs</a>, and maybe <a href="http://www.parrot.org/" rel="nofollow noreferrer">Parrot</a> (I didn\'t check it.)</p>\n\n<p><strong>Edit</strong></p>\n\n<p>This code also works.</p>\n\n<pre><code>sub postfix:&lt;!&gt; ($n) { [*] 1..$n }\n\n# This function(?) call like below ... It looks like mathematical notation.\nsay 10!;\n</code></pre>\n'}, {'answer_id': 216448, 'author': 'yfeldblum', 'author_id': 12349, 'author_profile': 'https://Stackoverflow.com/users/12349', 'pm_score': 2, 'selected': False, 'text': '<p>Haskell:</p>\n\n<pre><code>factorial n = product [1..n]\n</code></pre>\n'}, {'answer_id': 264821, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<h1><strong>Eiffel</strong></h1>\n\n<pre><code>\nclass\n    APPLICATION\ninherit\n    ARGUMENTS\n\ncreate\n    make\n\nfeature -- Initialization\n\n    make is\n            -- Run application.\n        local\n            l_fact: NATURAL_64\n        do\n            l_fact := factorial(argument(1).to_natural_64)\n            print("Result is: " + l_fact.out)\n        end\n\n    factorial(n: NATURAL_64): NATURAL_64 is\n            --\n        require\n            positive_n: n >= 0\n        do\n            if n = 0 then\n                Result := 1\n            else\n                Result := n * factorial(n-1)\n            end\n        end\n\nend -- class APPLICATION\n</code></pre>\n'}, {'answer_id': 287796, 'author': 'plinth', 'author_id': 20481, 'author_profile': 'https://Stackoverflow.com/users/20481', 'pm_score': 2, 'selected': False, 'text': '<h1>PostScript: Tail Recursive</h1>\n\n<pre><code>/fact0 { dup 2 lt { pop } { 2 copy mul 3 1 roll 1 sub exch pop fact0 } ifelse } def\n/fact { 1 exch fact0 } def\n</code></pre>\n'}, {'answer_id': 287816, 'author': 'BIBD', 'author_id': 685, 'author_profile': 'https://Stackoverflow.com/users/685', 'pm_score': 2, 'selected': False, 'text': '<h1>befunge-93</h1>\n\n<pre><code>                                    v\n&gt;v"Please enter a number (1-16) : "0&lt;\n,:             &gt;$*99g1-:99p#v_.25*,@\n^_&amp;:1-99p&gt;:1-:!|10          &lt; \n         ^     &lt;\n</code></pre>\n\n<p>An esoteric language by Chris Pressey of <a href="http://catseye.tc/" rel="nofollow noreferrer">Cat\'s Eye Technologies</a>.</p>\n'}, {'answer_id': 287921, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 1, 'selected': False, 'text': "<h1>dc</h1>\n\n<p>Note: clobbers the <code>e</code> and <code>f</code> registers:</p>\n\n<pre><code>[2++d]se[d1-d_1&lt;fd0&gt;e*]sf\n</code></pre>\n\n<p>To use, put the value you want to take the factorial of on the top of the stack and then execute <code>lfx</code> (load the <code>f</code> register and execute it), which then pops the top of the stack and pushes that value's factorial.</p>\n\n<p>Explanation: if the top of the stack is <code>x</code>, then the first part makes the top of the stack look like <code>(x, x-1)</code>.  If the new top-of-stack is non-negative, it calls factorial recursively, so now the stack is <code>(x, (x-1)!)</code> for <code>x</code> >= 1, or <code>(0, -1)</code> for <code>x</code> = 0.  Then, if the new top-of-stack is negative, it executes <code>2++d</code>, which replaces the <code>(0, -1)</code> with <code>(1, 1)</code>.  Finally, it multiplies the top two values on the stack.</p>\n"}, {'answer_id': 288143, 'author': 'tim_yates', 'author_id': 6509, 'author_profile': 'https://Stackoverflow.com/users/6509', 'pm_score': 1, 'selected': False, 'text': '<h1><a href="http://www.r-project.org/" rel="nofollow noreferrer">R</a> - using S4 methods (recursively)</h1>\n\n<pre><code>setGeneric( \'fct\', function( x ) { standardGeneric( \'fct\' ) } )\nsetMethod( \'fct\', \'numeric\', function( x ) { \n    lapply( x, function(a) { \n        if( a == 0 ) 1 else a * fact( a - 1 ) \n    } )\n} )\n</code></pre>\n\n<p>Has the advantage that you can pass arrays of numbers in, and it will work them all out...</p>\n\n<p>eg:</p>\n\n<pre><code>&gt; fct( c( 3, 5, 6 ) )\n[[1]]\n[1] 6\n\n[[2]]\n[1] 120\n\n[[3]]\n[1] 720\n</code></pre>\n'}, {'answer_id': 288232, 'author': 'runrig', 'author_id': 10415, 'author_profile': 'https://Stackoverflow.com/users/10415', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Perl (Y-combinator/Functional)</strong></p>\n\n<pre><code>print sub {\n  my $f = shift;\n  sub {\n    my $f1 = shift;\n    $f-&gt;( sub { $f1-&gt;( $f1 )-&gt;( @_ ) } )\n  }-&gt;( sub {\n    my $f2 = shift;\n    $f-&gt;( sub { $f2-&gt;( $f2 )-&gt;( @_ ) } )\n  } )\n}-&gt;( sub {\n  my $h = shift;\n  sub {\n    my $n = shift;\n    return 1 if $n &lt;=1;\n    return $n * $h-&gt;($n-1);\n  }\n})-&gt;(5);\n</code></pre>\n\n<p>Everything after \'print\' and before the \'->(5)\' represents the subroutine.\nThe factorial part is in the final "sub {...}". Everything else is to implement the Y-combinator.</p>\n'}, {'answer_id': 288395, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Forth (recursive):</p>\n\n<pre>\n: factorial ( n -- n )\n    dup 1 > if\n        dup 1 - recurse *\n    else\n        drop 1\n     then\n;</pre>\n'}, {'answer_id': 288461, 'author': 'Danko Durbić', 'author_id': 19241, 'author_profile': 'https://Stackoverflow.com/users/19241', 'pm_score': 4, 'selected': False, 'text': '<h2>XSLT 1.0</h2>\n<p>The input file, <strong>factorial.xml</strong>:</p>\n<pre><code>&lt;?xml version=&quot;1.0&quot;?&gt;\n&lt;?xml-stylesheet href=&quot;factorial.xsl&quot; type=&quot;text/xsl&quot; ?&gt;\n&lt;n&gt;\n  20\n&lt;/n&gt;\n</code></pre>\n<p>The XSLT file, <strong>factorial.xsl</strong>:</p>\n<pre><code>&lt;?xml version=&quot;1.0&quot;?&gt;\n&lt;xsl:stylesheet version=&quot;1.0&quot;                     \n                xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;\n                xmlns:msxsl=&quot;urn:schemas-microsoft-com:xslt&quot; &gt;\n  &lt;xsl:output method=&quot;text&quot;/&gt;\n  &lt;!-- 0! = 1 --&gt;\n  &lt;xsl:template match=&quot;text()[. = 0]&quot;&gt;\n    1\n  &lt;/xsl:template&gt;\n  &lt;!-- n! = (n-1)! * n--&gt;\n  &lt;xsl:template match=&quot;text()[. &gt; 0]&quot;&gt;\n    &lt;xsl:variable name=&quot;x&quot;&gt;\n      &lt;xsl:apply-templates select=&quot;msxsl:node-set( . - 1 )/text()&quot;/&gt;\n    &lt;/xsl:variable&gt;\n    &lt;xsl:value-of select=&quot;$x * .&quot;/&gt;\n  &lt;/xsl:template&gt;\n  &lt;!-- Calculate n! --&gt;\n  &lt;xsl:template match=&quot;/n&quot;&gt;\n    &lt;xsl:apply-templates select=&quot;text()&quot;/&gt;\n  &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n<p>Save both files in the same directory and open <strong>factorial.xml</strong> in IE.</p>\n'}, {'answer_id': 288596, 'author': 'geocar', 'author_id': 37507, 'author_profile': 'https://Stackoverflow.com/users/37507', 'pm_score': 2, 'selected': False, 'text': '<h1>J</h1>\n\n<pre><code>   fact=. verb define\n*/ &gt;:@i. y\n)\n</code></pre>\n'}, {'answer_id': 288688, 'author': 'Chris Dodd', 'author_id': 29759, 'author_profile': 'https://Stackoverflow.com/users/29759', 'pm_score': 1, 'selected': False, 'text': '<p>Iswim/Lucid:</p>\n\n<p><code>factorial = 1 fby factorial * (time+1);</code></p>\n'}, {'answer_id': 288712, 'author': 'user26294', 'author_id': 26294, 'author_profile': 'https://Stackoverflow.com/users/26294', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Python, one liner:</strong></p>\n\n<p>A bit more clean than the other python answer.\nThis, and the previous answer, will fail if the input is less than 1.</p>\n\n<p>def fact(n): return reduce(int.<strong>mul</strong>,xrange(2,n))</p>\n'}, {'answer_id': 288792, 'author': 'Brian Carper', 'author_id': 23070, 'author_profile': 'https://Stackoverflow.com/users/23070', 'pm_score': 2, 'selected': False, 'text': '<h1>Clojure</h1>\n\n<h2>Tail-recursive</h2>\n\n<pre><code>(defn fact \n  ([n] (fact n 1))\n  ([n acc] (if (= n 0) \n               acc \n               (recur (- n 1) (* acc n)))))\n</code></pre>\n\n<h2>Short and simple</h2>\n\n<pre><code> (defn fact [n] (apply * (range 1 (+ n 1))))\n</code></pre>\n'}, {'answer_id': 288834, 'author': 'Svante', 'author_id': 31615, 'author_profile': 'https://Stackoverflow.com/users/31615', 'pm_score': 1, 'selected': False, 'text': '<h1>Common Lisp</h1>\n\n<ul>\n<li>Call it by name: <code>!</code></li>\n<li>Tail recursive</li>\n<li>Common Lisp handles arbitrarily large numbers</li>\n</ul>\n\n<pre>\n(defun ! (n)\n  "factorial"\n  (labels ((fac (n prod)\n             (if (zerop n)\n                 prod\n                 (fac (- n 1) (* prod n)))))\n    (fac n 1)))\n</pre>\n\n<p><em>edit</em>:  or with accumulator as optional parameter:</p>\n\n<pre>\n(defun ! (n &optional prod)\n  "factorial"\n  (if (zerop n)\n      prod\n      (! (- n 1) (* prod n))))\n</pre>\n\n<p>or as a reduce, at the cost of a bigger memory footprint and more consing:</p>\n\n<pre>\n(defun range (start end &optional acc)\n  "range from start inclusive to end exclusive, start = start end)\n      (nreverse acc)\n      (range (+ start 1) end (cons start acc))))\n\n(defun ! (n)\n  "factorial"\n  (reduce #\'* (range 1 (+ n 1))))\n</pre>\n'}, {'answer_id': 289244, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<h1>Factor</h1>\n\n<p>USE: math.ranges</p>\n\n<p>: factorial ( n -- n! ) 1 [a,b] product ;</p>\n'}, {'answer_id': 289853, 'author': 'namin', 'author_id': 34596, 'author_profile': 'https://Stackoverflow.com/users/34596', 'pm_score': 2, 'selected': False, 'text': '<h1>Scala</h1>\n<p>The factorial can be defined functionally as:</p>\n<pre><code>def fact(n: Int): BigInt = 1 to n reduceLeft(_*_)\n</code></pre>\n<p>or more traditionally as</p>\n<pre><code>def fact(n: Int): BigInt = if (n == 0) 1 else fact(n-1) * n\n</code></pre>\n<p>and we can make ! a valid method on Ints:</p>\n<pre><code>object extendBuiltins extends Application {\n\n  class Factorizer(n: Int) {\n    def ! = 1 to n reduceLeft(_*_)\n  }\n\n  implicit def int2fact(n: Int) = new Factorizer(n)\n\n  println(&quot;10! = &quot; + (10!))\n}\n</code></pre>\n'}, {'answer_id': 289881, 'author': 'Chris Jefferson', 'author_id': 27074, 'author_profile': 'https://Stackoverflow.com/users/27074', 'pm_score': 2, 'selected': False, 'text': '<p>Compile time in C++</p>\n\n<pre><code>template&lt;unsigned i&gt;\nstruct factorial\n{ static const unsigned value = i * factorial&lt;i-1&gt;::value; };\n\ntemplate&lt;&gt;\nstruct factorial&lt;0&gt;\n{ static const unsigned value = 1; };\n</code></pre>\n\n<p>Use in code as:</p>\n\n<pre><code>Factorial&lt;5&gt;::value\n</code></pre>\n'}, {'answer_id': 290638, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<h1>Haskell</h1>\n\n<pre><code>factorial n = product [1..n]\n</code></pre>\n'}, {'answer_id': 290643, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Freshman Haskell programmer</p>\n\n<pre><code>fac n = if n == 0 \n           then 1\n           else n * fac (n-1)\n</code></pre>\n\n<p>Sophomore Haskell programmer, at MIT\n(studied Scheme as a freshman)</p>\n\n<pre><code>fac = (\\(n) -&gt;\n        (if ((==) n 0)\n            then 1\n            else ((*) n (fac ((-) n 1)))))\n</code></pre>\n\n<p>Junior Haskell programmer\n(beginning Peano player)</p>\n\n<pre><code>fac  0    =  1\nfac (n+1) = (n+1) * fac n\n</code></pre>\n\n<p>Another junior Haskell programmer\n(read that n+k patterns are “a disgusting part of Haskell” [1]\nand joined the “Ban n+k patterns”-movement [2])</p>\n\n<pre><code>fac 0 = 1\nfac n = n * fac (n-1)\n</code></pre>\n\n<p>Senior Haskell programmer\n(voted for   Nixon   Buchanan   Bush — “leans right”)</p>\n\n<pre><code>fac n = foldr (*) 1 [1..n]\n</code></pre>\n\n<p>Another senior Haskell programmer\n(voted for   McGovern   Biafra   Nader — “leans left”)</p>\n\n<pre><code>fac n = foldl (*) 1 [1..n]\n</code></pre>\n\n<p>Yet another senior Haskell programmer\n(leaned so far right he came back left again!)</p>\n\n<pre><code>-- using foldr to simulate foldl\n\nfac n = foldr (\\x g n -&gt; g (x*n)) id [1..n] 1\n</code></pre>\n\n<p>Memoizing Haskell programmer\n(takes Ginkgo Biloba daily)</p>\n\n<pre><code>facs = scanl (*) 1 [1..]\n\nfac n = facs !! n\n</code></pre>\n\n<p>Pointless (ahem) “Points-free” Haskell programmer\n(studied at Oxford)</p>\n\n<pre><code>fac = foldr (*) 1 . enumFromTo 1\n</code></pre>\n\n<p>Iterative Haskell programmer\n(former Pascal programmer)</p>\n\n<pre><code>fac n = result (for init next done)\n        where init = (0,1)\n              next   (i,m) = (i+1, m * (i+1))\n              done   (i,_) = i==n\n              result (_,m) = m\n\nfor i n d = until d n i\n</code></pre>\n\n<p>Iterative one-liner Haskell programmer\n(former APL and C programmer)</p>\n\n<pre><code>fac n = snd (until ((&gt;n) . fst) (\\(i,m) -&gt; (i+1, i*m)) (1,1))\n</code></pre>\n\n<p>Accumulating Haskell programmer\n(building up to a quick climax)</p>\n\n<pre><code>facAcc a 0 = a\nfacAcc a n = facAcc (n*a) (n-1)\n\nfac = facAcc 1\n</code></pre>\n\n<p>Continuation-passing Haskell programmer\n(raised RABBITS in early years, then moved to New Jersey)</p>\n\n<pre><code>facCps k 0 = k 1\nfacCps k n = facCps (k . (n *)) (n-1)\n\nfac = facCps id\n</code></pre>\n\n<p>Boy Scout Haskell programmer\n(likes tying knots; always “reverent,” he\nbelongs to the Church of the Least Fixed-Point [8])</p>\n\n<pre><code>y f = f (y f)\n\nfac = y (\\f n -&gt; if (n==0) then 1 else n * f (n-1))\n</code></pre>\n\n<p>Combinatory Haskell programmer\n(eschews variables, if not obfuscation;\nall this currying’s just a phase, though it seldom hinders)</p>\n\n<pre><code>s f g x = f x (g x)\n\nk x y   = x\n\nb f g x = f (g x)\n\nc f g x = f x g\n\ny f     = f (y f)\n\ncond p f g x = if p x then f x else g x\n\nfac  = y (b (cond ((==) 0) (k 1)) (b (s (*)) (c b pred)))\n</code></pre>\n\n<p>List-encoding Haskell programmer\n(prefers to count in unary)</p>\n\n<pre><code>arb = ()    -- "undefined" is also a good RHS, as is "arb" :)\n\nlistenc n = replicate n arb\nlistprj f = length . f . listenc\n\nlistprod xs ys = [ i (x,y) | x&lt;-xs, y&lt;-ys ]\n                 where i _ = arb\n\nfacl []         = listenc  1\nfacl n@(_:pred) = listprod n (facl pred)\n\nfac = listprj facl\n</code></pre>\n\n<p>Interpretive Haskell programmer\n(never “met a language” he didn\'t like)</p>\n\n<pre><code>-- a dynamically-typed term language\n\ndata Term = Occ Var\n          | Use Prim\n          | Lit Integer\n          | App Term Term\n          | Abs Var  Term\n          | Rec Var  Term\n\ntype Var  = String\ntype Prim = String\n\n\n-- a domain of values, including functions\n\ndata Value = Num  Integer\n           | Bool Bool\n           | Fun (Value -&gt; Value)\n\ninstance Show Value where\n  show (Num  n) = show n\n  show (Bool b) = show b\n  show (Fun  _) = ""\n\nprjFun (Fun f) = f\nprjFun  _      = error "bad function value"\n\nprjNum (Num n) = n\nprjNum  _      = error "bad numeric value"\n\nprjBool (Bool b) = b\nprjBool  _       = error "bad boolean value"\n\nbinOp inj f = Fun (\\i -&gt; (Fun (\\j -&gt; inj (f (prjNum i) (prjNum j)))))\n\n\n-- environments mapping variables to values\n\ntype Env = [(Var, Value)]\n\ngetval x env =  case lookup x env of\n                  Just v  -&gt; v\n                  Nothing -&gt; error ("no value for " ++ x)\n\n\n-- an environment-based evaluation function\n\neval env (Occ x) = getval x env\neval env (Use c) = getval c prims\neval env (Lit k) = Num k\neval env (App m n) = prjFun (eval env m) (eval env n)\neval env (Abs x m) = Fun  (\\v -&gt; eval ((x,v) : env) m)\neval env (Rec x m) = f where f = eval ((x,f) : env) m\n\n\n-- a (fixed) "environment" of language primitives\n\ntimes = binOp Num  (*)\n\nminus = binOp Num  (-)\nequal = binOp Bool (==)\ncond  = Fun (\\b -&gt; Fun (\\x -&gt; Fun (\\y -&gt; if (prjBool b) then x else y)))\n\nprims = [ ("*", times), ("-", minus), ("==", equal), ("if", cond) ]\n\n\n-- a term representing factorial and a "wrapper" for evaluation\n\nfacTerm = Rec "f" (Abs "n" \n              (App (App (App (Use "if")\n                   (App (App (Use "==") (Occ "n")) (Lit 0))) (Lit 1))\n                   (App (App (Use "*")  (Occ "n"))\n                        (App (Occ "f")  \n                             (App (App (Use "-") (Occ "n")) (Lit 1))))))\n\nfac n = prjNum (eval [] (App facTerm (Lit n)))\n</code></pre>\n\n<p>Static Haskell programmer\n(he does it with class, he’s got that fundep Jones!\nAfter Thomas Hallgren’s “Fun with Functional Dependencies” [7])</p>\n\n<pre><code>-- static Peano constructors and numerals\n\ndata Zero\ndata Succ n\n\ntype One   = Succ Zero\ntype Two   = Succ One\ntype Three = Succ Two\ntype Four  = Succ Three\n\n\n-- dynamic representatives for static Peanos\n\nzero  = undefined :: Zero\none   = undefined :: One\ntwo   = undefined :: Two\nthree = undefined :: Three\nfour  = undefined :: Four\n\n\n-- addition, a la Prolog\n\nclass Add a b c | a b -&gt; c where\n  add :: a -&gt; b -&gt; c\n\ninstance              Add  Zero    b  b\ninstance Add a b c =&gt; Add (Succ a) b (Succ c)\n\n\n-- multiplication, a la Prolog\n\nclass Mul a b c | a b -&gt; c where\n  mul :: a -&gt; b -&gt; c\n\ninstance                           Mul  Zero    b Zero\ninstance (Mul a b c, Add b c d) =&gt; Mul (Succ a) b d\n\n\n-- factorial, a la Prolog\n\nclass Fac a b | a -&gt; b where\n  fac :: a -&gt; b\n\ninstance                                Fac  Zero    One\ninstance (Fac n k, Mul (Succ n) k m) =&gt; Fac (Succ n) m\n\n-- try, for "instance" (sorry):\n-- \n--     :t fac four\n</code></pre>\n\n<p>Beginning graduate Haskell programmer\n(graduate education tends to liberate one from petty concerns\nabout, e.g., the efficiency of hardware-based integers)</p>\n\n<pre><code>-- the natural numbers, a la Peano\n\ndata Nat = Zero | Succ Nat\n\n\n-- iteration and some applications\n\niter z s  Zero    = z\niter z s (Succ n) = s (iter z s n)\n\nplus n = iter n     Succ\nmult n = iter Zero (plus n)\n\n\n-- primitive recursion\n\nprimrec z s  Zero    = z\nprimrec z s (Succ n) = s n (primrec z s n)\n\n\n-- two versions of factorial\n\nfac  = snd . iter (one, one) (\\(a,b) -&gt; (Succ a, mult a b))\nfac\' = primrec one (mult . Succ)\n\n\n-- for convenience and testing (try e.g. "fac five")\n\nint = iter 0 (1+)\n\ninstance Show Nat where\n  show = show . int\n\n(zero : one : two : three : four : five : _) = iterate Succ Zero\n</code></pre>\n\n<p>Origamist Haskell programmer\n(always starts out with the “basic Bird fold”)</p>\n\n<pre><code>-- (curried, list) fold and an application\n\nfold c n []     = n\nfold c n (x:xs) = c x (fold c n xs)\n\nprod = fold (*) 1\n\n\n-- (curried, boolean-based, list) unfold and an application\n\nunfold p f g x = \n  if p x \n     then [] \n     else f x : unfold p f g (g x)\n\ndownfrom = unfold (==0) id pred\n\n\n-- hylomorphisms, as-is or "unfolded" (ouch! sorry ...)\n\nrefold  c n p f g   = fold c n . unfold p f g\n\nrefold\' c n p f g x = \n  if p x \n     then n \n     else c (f x) (refold\' c n p f g (g x))\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac   = prod . downfrom\nfac\'  = refold  (*) 1 (==0) id pred\nfac\'\' = refold\' (*) 1 (==0) id pred\n</code></pre>\n\n<p>Cartesianally-inclined Haskell programmer\n(prefers Greek food, avoids the spicy Indian stuff;\ninspired by Lex Augusteijn’s “Sorting Morphisms” [3])</p>\n\n<pre><code>-- (product-based, list) catamorphisms and an application\n\ncata (n,c) []     = n\ncata (n,c) (x:xs) = c (x, cata (n,c) xs)\n\nmult = uncurry (*)\nprod = cata (1, mult)\n\n\n-- (co-product-based, list) anamorphisms and an application\n\nana f = either (const []) (cons . pair (id, ana f)) . f\n\ncons = uncurry (:)\n\ndownfrom = ana uncount\n\nuncount 0 = Left  ()\nuncount n = Right (n, n-1)\n\n\n-- two variations on list hylomorphisms\n\nhylo  f  g    = cata g . ana f\n\nhylo\' f (n,c) = either (const n) (c . pair (id, hylo\' f (c,n))) . f\n\npair (f,g) (x,y) = (f x, g y)\n\n\n-- several versions of factorial, all (extensionally) equivalent\n\nfac   = prod . downfrom\nfac\'  = hylo  uncount (1, mult)\nfac\'\' = hylo\' uncount (1, mult)\n</code></pre>\n\n<p>Ph.D. Haskell programmer\n(ate so many bananas that his eyes bugged out, now he needs new lenses!)</p>\n\n<pre><code>-- explicit type recursion based on functors\n\nnewtype Mu f = Mu (f (Mu f))  deriving Show\n\nin      x  = Mu x\nout (Mu x) = x\n\n\n-- cata- and ana-morphisms, now for *arbitrary* (regular) base functors\n\ncata phi = phi . fmap (cata phi) . out\nana  psi = in  . fmap (ana  psi) . psi\n\n\n-- base functor and data type for natural numbers,\n-- using a curried elimination operator\n\ndata N b = Zero | Succ b  deriving Show\n\ninstance Functor N where\n  fmap f = nelim Zero (Succ . f)\n\nnelim z s  Zero    = z\nnelim z s (Succ n) = s n\n\ntype Nat = Mu N\n\n\n-- conversion to internal numbers, conveniences and applications\n\nint = cata (nelim 0 (1+))\n\ninstance Show Nat where\n  show = show . int\n\nzero = in   Zero\nsuck = in . Succ       -- pardon my "French" (Prelude conflict)\n\nplus n = cata (nelim n     suck   )\nmult n = cata (nelim zero (plus n))\n\n\n-- base functor and data type for lists\n\ndata L a b = Nil | Cons a b  deriving Show\n\ninstance Functor (L a) where\n  fmap f = lelim Nil (\\a b -&gt; Cons a (f b))\n\nlelim n c  Nil       = n\nlelim n c (Cons a b) = c a b\n\ntype List a = Mu (L a)\n\n\n-- conversion to internal lists, conveniences and applications\n\nlist = cata (lelim [] (:))\n\ninstance Show a =&gt; Show (List a) where\n  show = show . list\n\nprod = cata (lelim (suck zero) mult)\n\nupto = ana (nelim Nil (diag (Cons . suck)) . out)\n\ndiag f x = f x x\n\nfac = prod . upto\n</code></pre>\n\n<p>Post-doc Haskell programmer\n(from Uustalu, Vene and Pardo’s “Recursion Schemes from Comonads” [4])</p>\n\n<pre><code>-- explicit type recursion with functors and catamorphisms\n\nnewtype Mu f = In (f (Mu f))\n\nunIn (In x) = x\n\ncata phi = phi . fmap (cata phi) . unIn\n\n\n-- base functor and data type for natural numbers,\n-- using locally-defined "eliminators"\n\ndata N c = Z | S c\n\ninstance Functor N where\n  fmap g  Z    = Z\n  fmap g (S x) = S (g x)\n\ntype Nat = Mu N\n\nzero   = In  Z\nsuck n = In (S n)\n\nadd m = cata phi where\n  phi  Z    = m\n  phi (S f) = suck f\n\nmult m = cata phi where\n  phi  Z    = zero\n  phi (S f) = add m f\n\n\n-- explicit products and their functorial action\n\ndata Prod e c = Pair c e\n\noutl (Pair x y) = x\noutr (Pair x y) = y\n\nfork f g x = Pair (f x) (g x)\n\ninstance Functor (Prod e) where\n  fmap g = fork (g . outl) outr\n\n\n-- comonads, the categorical "opposite" of monads\n\nclass Functor n =&gt; Comonad n where\n  extr :: n a -&gt; a\n  dupl :: n a -&gt; n (n a)\n\ninstance Comonad (Prod e) where\n  extr = outl\n  dupl = fork id outr\n\n\n-- generalized catamorphisms, zygomorphisms and paramorphisms\n\ngcata :: (Functor f, Comonad n) =&gt;\n           (forall a. f (n a) -&gt; n (f a))\n             -&gt; (f (n c) -&gt; c) -&gt; Mu f -&gt; c\n\ngcata dist phi = extr . cata (fmap phi . dist . fmap dupl)\n\nzygo chi = gcata (fork (fmap outl) (chi . fmap outr))\n\npara :: Functor f =&gt; (f (Prod (Mu f) c) -&gt; c) -&gt; Mu f -&gt; c\npara = zygo In\n\n\n-- factorial, the *hard* way!\n\nfac = para phi where\n  phi  Z             = suck zero\n  phi (S (Pair f n)) = mult f (suck n)\n\n\n-- for convenience and testing\n\nint = cata phi where\n  phi  Z    = 0\n  phi (S f) = 1 + f\n\ninstance Show (Mu N) where\n  show = show . int\n</code></pre>\n\n<p>Tenured professor\n(teaching Haskell to freshmen)</p>\n\n<pre><code>fac n = product [1..n]\n</code></pre>\n'}, {'answer_id': 292898, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 2, 'selected': False, 'text': '<h2>Smalltalk, using a closure</h2>\n\n<pre><code>    fac := [ :x | x = 0 ifTrue: [ 1 ] ifFalse: [ x * (fac value: x -1) ]].\n\n    Transcript show: (fac value: 24) "-&gt; 620448401733239439360000"\n</code></pre>\n\n<p>NB does not work in Squeak, requires full closures.</p>\n'}, {'answer_id': 292915, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 2, 'selected': False, 'text': '<h2>Smalltalk, memoized</h2>\n\n<p>Define a method on Dictionary</p>\n\n<pre><code>Dictionary &gt;&gt; fac: x\n    ^self at: x ifAbsentPut: [ x * (self fac: x - 1) ]\n</code></pre>\n\n<p>usage</p>\n\n<pre><code> d := Dictionary new.\n d at: 0 put: 1.\n d fac: 24 \n</code></pre>\n'}, {'answer_id': 292921, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 2, 'selected': False, 'text': '<h2>Smalltalk, 1-Liner</h2>\n\n<pre><code>(1 to: 24) inject: 1 into: [ :a :b | a * b ] \n</code></pre>\n'}, {'answer_id': 311784, 'author': 'Tony Lee', 'author_id': 5819, 'author_profile': 'https://Stackoverflow.com/users/5819', 'pm_score': 2, 'selected': False, 'text': '<p>Java Script: Creative method using "interview question" counting bits fnc.</p>\n\n<pre><code>function nu(x)\n{\n  var r=0\n  while( x ) {\n    x &amp;= x-1\n    r++\n  }\n  return r\n}\n\nfunction fac(n)\n{\n  var r= Math.pow(2,n-nu(n))\n\n  for ( var i=3 ; i &lt;= n ; i+= 2 )\n    r *= Math.pow(i,Math.floor(Math.log(n/i)/Math.LN2)+1)\n  return r\n}\n</code></pre>\n\n<p>Works up to 21! then Chrome switches to scientific notation.  Inspiration thanks lack of sleep and Knuth, et al\'s "concrete mathematics".</p>\n'}, {'answer_id': 311826, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 2, 'selected': False, 'text': '<p>Nothing is as fast as <strong>bash</strong> &amp; <strong>bc</strong>:</p>\n\n<pre><code>function fac { seq $1 | paste -sd* | bc; }  \n$ fac 42\n1405006117752879898543142606244511569936384000000000\n$\n</code></pre>\n'}, {'answer_id': 383858, 'author': 'Clayton', 'author_id': 22201, 'author_profile': 'https://Stackoverflow.com/users/22201', 'pm_score': 1, 'selected': False, 'text': '<p>In MUMPS:</p>\n\n<pre><code>fact(N)\n  N F,I S F=1 F  I=2:1:N S F=F*I\n  QUIT F\n</code></pre>\n\n<p>Or, if you\'re a fan of indirection:</p>\n\n<pre><code>fact(N)\n  N F,I S F=1 F I=2:1:N S F=F_"*"_I\n  QUIT @F\n</code></pre>\n'}, {'answer_id': 385519, 'author': 'dreeves', 'author_id': 4234, 'author_profile': 'https://Stackoverflow.com/users/4234', 'pm_score': 2, 'selected': False, 'text': "<h1>Mathematica: non-recursive</h1>\n\n<pre><code>fact[n_] := Times @@ Range[n]\n</code></pre>\n\n<p>Which is syntactic sugar for <code>Apply[Times, Range[n]]</code>.  I think that's the best way to do it, not counting the built-in <code>n!</code>, of course.  Note that that automatically uses bignums.</p>\n"}, {'answer_id': 393925, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Common Lisp version:</p>\n\n<pre><code>(defun ! (n) (reduce #'* (loop for i from 2 below (+ n 1) collect i)))\n</code></pre>\n\n<p>Seems to be quite fast.</p>\n\n<pre><code>* (! 42)\n\n1405006117752879898543142606244511569936384000000000\n</code></pre>\n"}, {'answer_id': 426478, 'author': 'Pål GD', 'author_id': 40058, 'author_profile': 'https://Stackoverflow.com/users/40058', 'pm_score': 0, 'selected': False, 'text': '<p>Common Lisp, since noone has commited that yet:</p>\n\n<pre><code>(defun factorial (n)\n  (if (&lt;= n 1)\n      1 \n      (* n (factorial (1- n)))))\n</code></pre>\n'}, {'answer_id': 432010, 'author': 'A. Rex', 'author_id': 3508, 'author_profile': 'https://Stackoverflow.com/users/3508', 'pm_score': 2, 'selected': False, 'text': '<h1>Brainfuck: with bignum support!</h1>\n\n<p>Accepts as input a non-negative integer followed by newline, and outputs the corresponding factorial followed by newline.</p>\n\n<pre><code>&gt;&gt;&gt;&gt;,----------[&gt;&gt;&gt;&gt;,----------]&gt;&gt;&gt;&gt;++&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;++++++[&lt;----\n--&gt;-]&lt;-&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;-&lt;[-]]&gt;[-]\n&gt;&gt;]&gt;[-&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&gt;&gt;]&gt;&gt;&gt;&gt;[-[&gt;+&lt;-]+&gt;&gt;&gt;\n&gt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[[&gt;&gt;&gt;&gt;+&lt;&lt;\n&lt;&lt;-]&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;-[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt;&gt;\n+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-]&lt;-[&gt;&gt;+&lt;&lt;[-]]&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[&gt;[&gt;+&lt;-]&gt;[&lt;&lt;+&gt;+&gt;\n-]&lt;&lt;[&gt;&gt;&gt;+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-]&lt;-&gt;+++++++++[-&lt;[-[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;-]]&gt;&gt;\n&gt;&gt;[&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;]&lt;[&gt;&gt;+&lt;&lt;&lt;&lt;[-]&gt;&gt;[&lt;&lt;+&gt;&gt;-]]&gt;&gt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;[&lt;&lt;\n&lt;&lt;]&gt;&gt;&gt;&gt;-]&gt;&gt;&gt;&gt;]&gt;&gt;&gt;[&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;-&lt;[-\n]]&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;-[\n&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]+&lt;[&gt;-&lt;[-]]&gt;[-&lt;&lt;++++++++++&lt;&lt;&lt;&lt;-[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;\n&lt;+&gt;+&gt;-]+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;&gt;&gt;\n&gt;+&lt;&lt;&lt;-&lt;[-]]&gt;[-]&gt;&gt;]&gt;]&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;+++++++[&lt;+++++++&gt;-]&lt;--.&lt;&lt;\n&lt;&lt;]++++++++++.\n</code></pre>\n\n<p>Unlike the brainf*ck answer posted earlier, this <em>does not</em> overflow any memory locations.  (That implementation put n! in a single memory location, effectively limiting it to n less than 6 under standard bf rules.)  This program will output n! for any value of n, limited only by time and memory (or bf implementation).  For example, using Urban Muller\'s compiler on my machine, it takes 12 seconds to compute 1000!  I think that\'s pretty good, considering the program can only move left/right and increment/decrement by one.</p>\n\n<p>Believe it or not, this is the first bf program I\'ve written; it took about 10 hours, which were mostly spent debugging.  Unfortunately, I later found out that Daniel B Cristofani has written a <a href="http://www.hevanet.com/cristofd/brainfuck/factorial.b" rel="nofollow noreferrer">factorial generator</a>, which just outputs ever-larger factorials, never terminating:</p>\n\n<pre><code>&gt;++++++++++&gt;&gt;&gt;+&gt;+[&gt;&gt;&gt;+[-[&lt;&lt;&lt;&lt;&lt;[+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;[[-]&gt;[&lt;&lt;+&gt;+&gt;-]&lt;[&gt;+&lt;-\n]&lt;[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;+&lt;-[&gt;[-]&gt;&gt;&gt;&gt;+&gt;+&lt;\n&lt;&lt;&lt;&lt;&lt;-[&gt;+&lt;-]]]]]]]]]]]&gt;[&lt;+&gt;-]+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;\n&gt;]++[-&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;-]+&gt;&gt;&gt;&gt;&gt;]&lt;[&gt;++&lt;-]&lt;&lt;&lt;&lt;[&lt;[&gt;+&lt;-]&lt;&lt;&lt;&lt;]&gt;&gt;[-&gt;[-]\n++++++[&lt;++++++++&gt;-]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[&lt;[&gt;+&gt;+&lt;&lt;-]&gt;.&lt;&lt;&lt;&lt;&lt;]&gt;.&gt;&gt;&gt;&gt;]\n</code></pre>\n\n<p>His program is much shorter, but he\'s practically a professional bf golfer.</p>\n'}, {'answer_id': 441229, 'author': 'A. Rex', 'author_id': 3508, 'author_profile': 'https://Stackoverflow.com/users/3508', 'pm_score': 9, 'selected': True, 'text': '<h1>Polyglot: 5 languages, all using bignums</h1>\n\n<p>So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today.  It\'s a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial.  Bignums are used in all languages, so the maximum computable factorial depends only on your computer\'s resources.</p>\n\n<ul>\n<li><b>Perl</b>: uses built-in bignum package.  Run with <code>perl FILENAME</code>.</li>\n<li><b>Haskell</b>: uses built-in bignums.  Run with <code>runhugs FILENAME</code> or your favorite compiler\'s equivalent.</li>\n<li><b>C++</b>: requires GMP for bignum support.  To compile with g++, use <code>g++ -lgmpxx -lgmp -x c++ FILENAME</code> to link against the right libraries.  After compiling, run <code>./a.out</code>.  Or use your favorite compiler\'s equivalent.</li>\n<li><b>brainf*ck</b>: I wrote some bignum support in <a href="https://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages/432010#432010">this post</a>.  Using <a href="http://aminet.net/package.php?package=dev/lang/brainfuck-2.lha" rel="nofollow noreferrer">Muller\'s classic distribution</a>, compile with <code>bf &lt; FILENAME &gt; EXECUTABLE</code>.  Make the output executable and run it.  Or use your favorite distribution.</li>\n<li><b>Whitespace</b>: uses built-in bignum support.  Run with <code>wspace FILENAME</code>.</li>\n</ul>\n\n<p><i>Edit:</i> added Whitespace as a fifth language.  Incidentally, do <em>not</em> wrap the code with <code>&lt;code&gt;</code> tags; it breaks the Whitespace.  Also, the code looks much nicer in fixed-width.</p>\n\n<pre>char&#32;//#&#32;b=0+0{-&#32;|0*/;&#32;#&gt;&gt;&gt;&gt;,----------[&gt;&gt;&gt;&gt;,--------\n#define&#09;a/*#--]&gt;&gt;&gt;&gt;++&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;++++++[&lt;------&gt;-]&lt;-&lt;&lt;&lt;\n#Perl&#09;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&#09;&#32;&lt;&gt;&#32;&lt;&gt;&#32;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;\n#C++&#09;--&gt;&lt;&gt;&lt;&gt;&#09;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&#09;&gt;&#32;&lt;&#32;&gt;&#32;&lt;&#09;+&lt;[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;-&lt;[-]]&gt;[-]\n#Haskell&#32;&gt;&gt;]&gt;[-&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]&gt;&gt;]\n#Whitespace&#09;&gt;&gt;&gt;&gt;[-[&gt;+&lt;-]+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;\n#brainf*ck&#32;&gt;&#32;&lt;&#32;]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[[&gt;&gt;&gt;&gt;*/\nexp;&#32;;//;#+&lt;&lt;&lt;&lt;-]&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;][.POLYGLOT^5.\n#include&#32;&lt;gmpxx.h&gt;//]&gt;&gt;&gt;&gt;-[&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt;\n#define&#09;eval&#32;int&#09;main()//&gt;+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-&gt;\n#include&#32;&lt;iostream&gt;//&lt;]&lt;-[&gt;&gt;+&lt;&lt;[-]]&lt;&lt;[&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[&gt;[&gt;&gt;&gt;\n#define&#09;print&#32;std::cout&#09;&lt;&lt;&#32;//&#32;&gt;&#09;&lt;+&lt;-]&gt;[&lt;&lt;+&gt;+&gt;-]&lt;&lt;[&gt;&gt;&gt;\n#define&#09;z&#32;std::cin&gt;&gt;//&lt;&lt;&#32;+&lt;&lt;&lt;-]&gt;&gt;&gt;[&lt;&lt;&lt;+&gt;&gt;+&gt;-]&lt;-&gt;+++++\n#define&#32;c/*++++[-&lt;[-[&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;-]]&gt;&gt;&gt;&gt;[&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;*/\n#define&#09;abs&#32;int&#32;$n&#32;//&gt;&lt;&#09;&lt;]&lt;[&gt;&gt;+&lt;&lt;&lt;&lt;[-]&gt;&gt;[&lt;&lt;+&gt;&gt;-]]&gt;&gt;]&lt;\n#define&#09;uc&#32;mpz_class&#32;fact(int&#09;$n){/*&lt;&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;[&lt;&lt;\nuse&#32;bignum;sub#&lt;&lt;]&gt;&gt;&gt;&gt;-]&gt;&gt;&gt;&gt;]&gt;&gt;&gt;[&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-]\nz{$_[0+0]=readline(*STDIN);}sub&#32;fact{my($n)=shift;#&gt;&gt;\n#[&lt;&lt;+&gt;+&gt;-]&lt;-&gt;+&lt;[&gt;-&lt;[-]]&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;+*/\nuc;if($n==0){return&#32;1;}return&#32;$n*fact($n-1);&#09;}//;#\neval{abs;z($n);print&#32;fact($n);print("\\n")/*2;};#-]&lt;-&gt;\n\'+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;-[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-]+&lt;[&gt;-+++\n-}--&#09;&lt;[-]]&gt;[-&lt;&lt;++++++++++&lt;&lt;&lt;&lt;-[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+&gt;-++\nfact&#32;0&#09;=&#32;1&#32;--&#32;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&#09;&gt;&#32;&lt;&gt;&lt;&gt;&lt;&#09;]+&lt;[&gt;-&lt;[-]]&gt;]&lt;&lt;[&lt;&lt;+&#32;+\nfact&#09;n=n*fact(n-1){-&lt;&lt;]&gt;&gt;&gt;&gt;[[&gt;&gt;+&lt;&lt;-]&gt;&gt;[&lt;&lt;+&gt;+++&gt;+-}\nmain=do{n&lt;-readLn;print(fact&#32;n)}--&#32;+&gt;-]&lt;-&gt;+&lt;[&gt;&gt;&gt;&gt;+&lt;&lt;+\n{-x&lt;-&lt;[-]]&gt;[-]&gt;&gt;]&gt;]&gt;&gt;&gt;[&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[&gt;+++++++[&lt;+++++++&gt;-]\n&lt;--.&lt;&lt;&lt;&lt;]+written+by+++A+Rex+++2009+.\';#+++x-}--x*/;}\n</pre>\n'}, {'answer_id': 450128, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><strong>ActionScript: Procedural/OOP</strong></p>\n\n<pre><code>function f(n) {\n    var result = n&gt;1 ? arguments.callee(n-1)*n : 1;\n    return result;\n}\n// function call\nf(3);\n</code></pre>\n'}, {'answer_id': 514922, 'author': 'Phil', 'author_id': 62789, 'author_profile': 'https://Stackoverflow.com/users/62789', 'pm_score': 0, 'selected': False, 'text': '<h1>Common Lisp</h1>\n\n<p>I\'m fairly sure this could be more effieicnet. It is my first lisp function other than "hello, world" and typing in the example code in the third chapter. <em>Practical Common Lisp</em> is a great text. This function does seem to handle large factorials well.</p>\n\n<pre><code>(defun factorial (x)\n  (if (&lt; x 2) (return-from factorial (print 1)))\n  (let ((tempx 1) (ans 1))\n  (loop until (equalp x tempx) do\n       (incf tempx)\n       (setf ans (* tempx ans)))\n  (list ans)))\n</code></pre>\n'}, {'answer_id': 546268, 'author': 'stevenvh', 'author_id': 66056, 'author_profile': 'https://Stackoverflow.com/users/66056', 'pm_score': 2, 'selected': False, 'text': "<h1>Delphi iterative</h1>\n\n<p>While recursion can be the only decent solution to a problem, for factorials it is not. To describe it, yes. To program it, no. Iteration is cheapest.</p>\n\n<p>This function calculates factorials for somewhat larger arguments.</p>\n\n<pre><code>function Factorial(aNumber: Int64): String;\nvar\n  F: Double;\nbegin\n  F := 0;\n  while aNumber &gt; 1 do begin\n    F := F + log10(aNumber);\n    dec(aNumber);\n  end;\n  Result := FloatToStr(Power(10, Frac(F))) + ' * 10^' + IntToStr(Trunc(F));\nend;\n</code></pre>\n\n<p>1000000! = 8.2639327850046 * 10^5565708</p>\n"}, {'answer_id': 576331, 'author': 'SingleNegationElimination', 'author_id': 65696, 'author_profile': 'https://Stackoverflow.com/users/65696', 'pm_score': 1, 'selected': False, 'text': "<p>Hmm... no TCL</p>\n\n<pre><code>proc factorial {n} {\n  if { $n == 0 } { return 1 }\n  return [expr {$n*[factorial [expr {$n-1}]]}]\n}\nputs [factorial 6]\n</code></pre>\n\n<p>But of course that doesn't work for a damn for large values of n.... we can do better with tcllib!</p>\n\n<pre><code>package require math::bignum\nproc factorial {n} {\n  if { $n == 0 } { return 1 }\n  return [ ::math::bignum::tostr [ ::math::bignum::mul [\n    ::math::bignum::fromstr $n] [ ::math::bignum::fromstr [\n      factorial [expr {$n-1} ]\n    ]]]]\n}\nputs [factorial 60]\n</code></pre>\n\n<p>Look at all those ]'s at the end.  This is practically LISP!</p>\n\n<p>I'll leave the version for values of n>2^32 as an excersize for the reader</p>\n"}, {'answer_id': 576336, 'author': 'mweiss', 'author_id': 33254, 'author_profile': 'https://Stackoverflow.com/users/33254', 'pm_score': 2, 'selected': False, 'text': '<h1>Logo</h1>\n\n<pre><code>? to factorial :n\n&gt; ifelse :n = 0 [output 1] [output :n * factorial :n - 1]\n&gt; end\n</code></pre>\n\n<p>And to invoke:</p>\n\n<pre><code>? print factorial 5\n120\n</code></pre>\n\n<p>This is using the UCBLogo dialect of logo.</p>\n'}, {'answer_id': 673795, 'author': 'jfklein', 'author_id': 72919, 'author_profile': 'https://Stackoverflow.com/users/72919', 'pm_score': 1, 'selected': False, 'text': "<h1>Mathematica, Memoized</h1>\n\n<pre><code>f[n_ /; n &lt; 2] := 1\nf[n_] := (f[n] = n*f[n - 1])\n</code></pre>\n\n<p>Mathematica supports n! natively, but this shows how to make definitions on the fly.  When you execute f[2], this code will make a definition f[2]=2 which will subsequently be executed no differently than if you'd hard-coded it; no need for an internal data structure; you just use the language's own function definition machinery.</p>\n"}, {'answer_id': 690619, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Lisp : tail-recursive</strong></p>\n\n<pre><code>(defun factorial(x)\n  (labels((f (x acc)\n             (if (&gt; x 1)\n                 (f (1- x)(* x acc))\n                 acc)))\n         (f x 1)))\n</code></pre>\n'}, {'answer_id': 827102, 'author': 'fishlips', 'author_id': 101790, 'author_profile': 'https://Stackoverflow.com/users/101790', 'pm_score': 2, 'selected': False, 'text': '<h2>Agda2</h2>\n\n<p>It is Agda2, using the very nice Agda2 syntax.</p>\n\n<pre><code>module fac where\n\ndata Nat : Set where        -- Peano numbers\n  zero : Nat\n  suc : Nat -&gt; Nat\n{-# BUILTIN NATURAL Nat #-}\n{-# BUILTIN SUC suc #-}\n{-# BUILTIN ZERO zero #-}\n\ninfixl 10 _+_               -- Addition over Peano numbers\n_+_ : Nat -&gt; Nat -&gt; Nat\nzero + n    = n\n(suc n) + m = suc (n + m)\n\ninfixl 20 _*_               -- Multiplication over Peano numbers\n_*_ : Nat -&gt; Nat -&gt; Nat\nzero * n = zero\nn * zero = zero\n(suc n) * (suc m) = suc n + (suc n * m)\n\n_! : Nat -&gt; Nat             -- Factorial function, syntax: "x !"\nzero ! = suc zero\n(suc n) ! = (suc n) * (n !)\n</code></pre>\n'}, {'answer_id': 827173, 'author': 'Daniel Huckstep', 'author_id': 4657, 'author_profile': 'https://Stackoverflow.com/users/4657', 'pm_score': 1, 'selected': False, 'text': '<p>Another ruby one.</p>\n\n<pre><code>class Integer\n  def fact\n    return 1 if self.zero?\n    (1..self).to_a.inject(:*)\n  end\nend</code></pre>\n\n<p>This works if to_proc is supported on symbols.</p>\n'}, {'answer_id': 831961, 'author': 'ijw', 'author_id': 87583, 'author_profile': 'https://Stackoverflow.com/users/87583', 'pm_score': 2, 'selected': False, 'text': "<p>Perl, pessimal:</p>\n\n<pre><code># Because there are just so many other ways to get programs wrong...\nuse strict;\nuse warnings;\n\nsub factorial {\n    my ($x)=@_;\n\n    for(my $f=1;;$f++) {\n        my $tmp=$f;\n        foreach my $g (1..$x) {\n           $tmp/=$g;\n        }\n        return $f if $tmp == 1;\n    }\n}\n</code></pre>\n\n<p>I trust I get extra points for not using the '*' operator...</p>\n"}, {'answer_id': 992379, 'author': 'Gregory Higley', 'author_id': 27779, 'author_profile': 'https://Stackoverflow.com/users/27779', 'pm_score': 1, 'selected': False, 'text': '<h1>REBOL</h1>\n\n<p>Math is <em>definitely</em> not one of REBOL\'s strong points, since it lacks arbitrary precision integers. For the sake of completeness, I thought I\'d add it anyway.</p>\n\n<p>Here\'s a standard, na&iuml;ve recursive implementation:</p>\n\n<pre>fac: func [ [catch] n [integer!] ] [\n    if n &lt; 0 [ throw make error! "Hey dummy, your argument was less than 0!" ]\n    either n = 0 [ 1 ] [\n        n * fac (n - 1)\n    ]\n]</pre>\n\n<p>And that\'s about it. Move along, folks, nothing to see here ... :)</p>\n'}, {'answer_id': 1244406, 'author': 'nes1983', 'author_id': 52573, 'author_profile': 'https://Stackoverflow.com/users/52573', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s my proposal. Runs in Mathematica, works fine:</p>\n\n<pre><code>gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},\n  visit[k_] := Module[{t},\n    id++; If[k != 0, val[[k]] = id];\n    If[id == n, f[val]];\n    Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];\n    id--; val[[k]] = Null;];\n  visit[0];\n  ]\n\nFactorial[n_] := Module[{res=0}, gen[res++&amp;, n]; res]\n</code></pre>\n\n<p><strong>Update</strong>\nOk, here\'s how it works: the visit function is from Sedgewick\'s Algorithm book, it "visits" all permutations of length n. Upon the visit, it calls function f with the permutation as an argument. </p>\n\n<p>So, Factorial enumerates all permutations of length n, and for each permutation the counter res is increased, thus computing n! in O(n+1)! time.</p>\n'}, {'answer_id': 1244623, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Python: </p>\n\n<pre><code>def factorial(n):\n    return reduce(lambda x, y: x * y,range(1, n + 1))\n</code></pre>\n'}, {'answer_id': 1653893, 'author': 'Alix Axel', 'author_id': 89771, 'author_profile': 'https://Stackoverflow.com/users/89771', 'pm_score': 1, 'selected': False, 'text': "<h1>PHP - 59 chars</h1>\n<pre><code>function f($n){return array_reduce(range(1,$n),'bcmul',1);}\n</code></pre>\n<hr />\n<h1>Improved Version - 27 chars</h1>\n<pre><code>array_product(range(1,$n));\n</code></pre>\n"}, {'answer_id': 1743311, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p><strong>*NIX Shell</strong></p>\n\n<p>Linux version:</p>\n\n<pre><code>seq -s'*' 42 | bc\n</code></pre>\n\n<p>BSD version:</p>\n\n<pre><code>jot -s'*' 42 | bc\n</code></pre>\n"}, {'answer_id': 1743353, 'author': 'finnw', 'author_id': 12048, 'author_profile': 'https://Stackoverflow.com/users/12048', 'pm_score': 1, 'selected': False, 'text': '<h2>SETL</h2>\n\n<p>...where Haskell and Python borrowed their list comprehensions from.</p>\n\n<pre><code>proc factorial(n);\n    return 1 */ {1..n};\nend factorial;\n</code></pre>\n\n<p>And the built-in <code>INTEGER</code> type is arbitrary-precision, so this will work for any positive <code>n</code>.</p>\n'}, {'answer_id': 2126153, 'author': 'Thomas Eding', 'author_id': 239916, 'author_profile': 'https://Stackoverflow.com/users/239916', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://esolangs.org/wiki/Befunge" rel="nofollow noreferrer"><strong><h1>Befunge:</h1></strong></a></p>\n\n<pre><code>0&amp;&gt;:1-:v v *_$.@ \n  ^    _$&gt;\\:^\n</code></pre>\n'}, {'answer_id': 2126202, 'author': 'Ken', 'author_id': 230831, 'author_profile': 'https://Stackoverflow.com/users/230831', 'pm_score': 1, 'selected': False, 'text': "<h2>CLOS</h2>\n\n<p>I see Common Lisp solutions abusing recursion, LOOP, and even FORMAT.  I guess it's time for somebody to write a solution that abuses CLOS!</p>\n\n<pre><code>(defgeneric factorial (n))\n(defmethod factorial ((n (eql 0))) 1)\n(defmethod factorial ((n integer)) (* n (factorial (1- n))))\n</code></pre>\n\n<p>(Can your favorite language's object system dispatcher do that?)</p>\n"}, {'answer_id': 2298931, 'author': 'Lynn', 'author_id': 257418, 'author_profile': 'https://Stackoverflow.com/users/257418', 'pm_score': 1, 'selected': False, 'text': '<h1>Golfscript: designed for golfing, of course</h1>\n\n<pre><code>~),1&gt;{*}*\n</code></pre>\n\n<ul>\n<li><code>~</code> evaluates the input string (to an integer)</li>\n<li><code>)</code> increments the number</li>\n<li><code>,</code> is range (4, becomes [0 1 2 3])</li>\n<li><code>1&gt;</code> selects values whose index is 1 or bigger</li>\n<li><code>{*}*</code> folds multiplication over the list</li>\n<li>Stack contents are printed when the program terminates.</li>\n</ul>\n\n<p>To run:</p>\n\n<pre><code>echo 5 | ruby gs.rb fact.gs\n</code></pre>\n'}, {'answer_id': 2299240, 'author': 'plinth', 'author_id': 20481, 'author_profile': 'https://Stackoverflow.com/users/20481', 'pm_score': 2, 'selected': False, 'text': '<p>FORTH, iterative 1 liner</p>\n\n<pre><code>: FACT 1 SWAP 1 + 1 DO I * LOOP ;\n</code></pre>\n'}, {'answer_id': 2299739, 'author': 'Paul', 'author_id': 103081, 'author_profile': 'https://Stackoverflow.com/users/103081', 'pm_score': 1, 'selected': False, 'text': '<h2>Oh fork() its another example in Perl</h2>\n\n<p>This will make use of your multiple core CPUs... although perhaps not in the most effective manner.  The <em>open</em> statement clones the process with fork and opens a pipe from the child process to the parent. The work of multiplying numbers 2 at a time is split among a tree of very short lived processes. Of course, this example is a bit silly. The point is that if you actually had more difficult calculations to do then this example illustrates one way to divide up the work in parallel.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse bigint;\n\nprint STDOUT &amp;main::rangeProduct(1,$ARGV[0])."\\n";\n\nsub main::rangeProduct {\n    my($l, $h) = @_;\n    return $l    if ($l==$h);\n    return $l*$h if ($l==($h-1));\n    # arghhh - multiplying more than 2 numbers at a time is too much work\n    # find the midpoint and split the work up :-)\n    my $m = int(($h+$l)/2);\n    my $pid = open(my $KID, "-|");\n      if ($pid){ # parent\n        my $X = &amp;main::rangeProduct($l,$m);\n        my $Y = &lt;$KID&gt;;\n        chomp($Y);\n        close($KID);\n        die "kid failed" unless defined $Y;\n        return $X*$Y;\n      } else {\n        # kid\n        print STDOUT &amp;main::rangeProduct($m+1,$h)."\\n";\n        exit(0);\n    }\n}\n</code></pre>\n'}, {'answer_id': 3026710, 'author': 'James Mills', 'author_id': 364980, 'author_profile': 'https://Stackoverflow.com/users/364980', 'pm_score': 0, 'selected': False, 'text': '<p>In <a href="http://iolanguage.org/" rel="nofollow noreferrer">Io</a>:</p>\n\n<pre><code>factorial := method(n,\n    if (list(0, 1) contains(n),\n       1,\n       n * factorial(n - 1)\n    )\n)\n</code></pre>\n'}, {'answer_id': 3026924, 'author': 'erjiang', 'author_id': 140827, 'author_profile': 'https://Stackoverflow.com/users/140827', 'pm_score': 2, 'selected': False, 'text': '<h1>Scheme evolution</h1>\n\n<h2>Regular Scheme program:</h2>\n\n<pre><code>(define factorial\n   (lambda (n)\n     (if (= n 0)\n         1\n         (* n (factorial (- n 1))))))\n</code></pre>\n\n<p>Should work, but notice that calling this function on large numbers will extend the stack on every recursion, which is bad in languages like C and Java.</p>\n\n<h2>Continuation-passing style</h2>\n\n<pre><code>(define factorial\n  (lambda (n)\n    (factorial_cps n (lambda (k) k))))\n\n(define factorial_cps\n  (lambda (n k)\n    (if (zero? n)\n        (k 1)\n        (factorial (- n 1) (lambda (v)\n                             (k (* n v)))))))\n</code></pre>\n\n<p>Ah, this way, we don\'t grow our stack every recursion because we can extend a continuation instead.  However, C doesn\'t have continuations.</p>\n\n<h2>Representation-independent CPS</h2>\n\n<pre><code>(define factorial\n  (lambda (n)\n    (factorial_cps n (k_))))\n\n(define factorial_cps\n  (lambda (n k)\n    (if (zero? n)\n        (apply_k 1)\n        (factorial (- n 1) (k_extend n k))))\n\n(define apply_k\n  (lambda (ko v)\n    (ko v)))\n(define kt_empty\n  (lambda ()\n    (lambda (v) v)))\n(define kt_extend \n  (lambda ()\n    (lambda (v)\n      (apply_k k (* n v)))))\n</code></pre>\n\n<p>Notice that responsibility for representation of the continuations used in the original CPS program has been shifted to the <code>kt_</code> helper procedures.</p>\n\n<h2>Representation-independent CPS using ParentheC unions</h2>\n\n<p>Since representation of the continuations is in the helper procedures, we can switch to using <a href="https://www.cs.indiana.edu/cgi-pub/lkuper/b521/_media/parenthec.pdf" rel="nofollow noreferrer">ParentheC</a> instead, with <code>kt_</code> being a type designator. </p>\n\n<pre><code>(define factorial\n  (lambda (n)\n    (factorial_cps n (kt_empty))))\n\n(define factorial_cps\n  (lambda (n k)\n    (if (zero? n)\n        (apply_k 1)\n        (factorial (- n 1) (kt_extend n k))))\n\n(define-union kt\n  (empty)\n  (extend n k))\n(define apply_k\n  (lambda ()\n    (union-case kh kt\n      [(empty) v]\n      [(extend n k) (begin\n                      (set! kh k)\n                      (set! v (* n v))\n                      (apply_k))])))\n</code></pre>\n\n<h2>Trampolined, registerized ParentheC program</h2>\n\n<p>That\'s not enough.  We now replace all function calls by instead setting global variables and a program counter.  Procedures are now labels suitable for GOTO statements.</p>\n\n<pre><code>(define-registers n k kh v)\n(define-program-counter pc)\n\n(define-label main\n  (begin\n    (set! n 5) ; what is the factorial of 5??\n    (set! pc factorial_cps)\n    (mount-trampoline kt_empty k pc)\n    (printf "Factorial of 5: ~d\\n" v)))\n\n(define-label factorial_cps\n  (if (zero? n)\n      (begin\n        (set! kh k)\n        (set! v 1)\n        (set! pc apply_k))\n      (begin\n        (set! k (kt_extend n k))\n        (set! n (- n 1))\n        (set! pc factorial_cps))))\n\n(define-union kt\n  (empty dismount) ; get off the trampoline!\n  (extend n k))\n\n(define-label apply_k\n  (union-case kh kt\n    [(empty dismount) (dismount-trampoline dismount)]\n    [(extend n k) (begin\n                    (set! kh k)\n                    (set! v (* n v))\n                    (set! pc apply_k))]))\n</code></pre>\n\n<p>Oh look, we have a <code>main</code> procedure now too.  Now all that\'s left to do is save this file as <code>fact5.pc</code> and run it through ParentheC\'s pc2c:</p>\n\n<pre><code>&gt; (load "pc2c.ss")\n&gt; (pc2c "fact5.pc" "fact5.c" "fact5.h")\n</code></pre>\n\n<p>Could it be?  We got <code>fact5.c</code> and <code>fact5.h</code>.  Let\'s see...</p>\n\n<pre><code>$ gcc fact5.c -o fact5\n$ ./fact5\nFactorial of 5: 120\n</code></pre>\n\n<p>Success! We have converted a recursive Scheme program into a non-recursive C program! And it only took several hours and many forehead-shaped impressions in the wall to do it!  For convenience, <a href="http://pastebin.ca/1881437" rel="nofollow noreferrer">fact5.c</a> and \n and <a href="http://pastebin.ca/1881438" rel="nofollow noreferrer">fact5.h</a>.</p>\n'}, {'answer_id': 3230390, 'author': 'Robert William Hanks', 'author_id': 350331, 'author_profile': 'https://Stackoverflow.com/users/350331', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Python:</strong>\nfunctional, recursive one-liner using short circuit boolean evaluation.</p>\n\n<pre><code>    factorial = lambda n: ((n &lt;= 1) and 1) or factorial(n-1) * n\n</code></pre>\n'}, {'answer_id': 5759098, 'author': 'Anthony Faull', 'author_id': 63264, 'author_profile': 'https://Stackoverflow.com/users/63264', 'pm_score': 1, 'selected': False, 'text': '<h1>T-SQL: Recursive CTE</h1>\n<p>Inline table function using a recursive common table expression. SQL Server 2005 and up.</p>\n<pre><code>CREATE FUNCTION dbo.Factorial(@n int) RETURNS TABLE\nAS\nRETURN\n    WITH RecursiveCTE (N, Value) AS\n    (\n        SELECT 1, CAST(1 AS decimal(38,0))\n        UNION ALL\n        SELECT N+1, CAST(Value*(N+1) AS decimal(38,0))\n        FROM RecursiveCTE\n    )\n    SELECT TOP 1 Value\n    FROM RecursiveCTE\n    WHERE N = @n\n</code></pre>\n'}, {'answer_id': 8297255, 'author': 'NoSenseEtAl', 'author_id': 700825, 'author_profile': 'https://Stackoverflow.com/users/700825', 'pm_score': 0, 'selected': False, 'text': '<p>C++ constexpr</p>\n\n<pre><code>constexpr uint64_t fact(uint32_t n)\n{\n    return  (n==0) ? 1:n*fact(n-1);\n}\n</code></pre>\n'}, {'answer_id': 9284383, 'author': 'iSun', 'author_id': 960097, 'author_profile': 'https://Stackoverflow.com/users/960097', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Vb6 :</strong></p>\n\n<pre><code>Private Function factCalculation(ByVal Number%)\n  Dim intNum%\n  intNum = 1\n  For i = 2 To Number\n     intNum = intNum * Number\n  Next i\n  return intNum\nEnd Function\n\nPrivate Sub Form_Load()\n Dim FactResult% : FactResult = factCalculation(3) 'e.g\n Print FactResult\nEnd Sub\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/23930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1337/']