Factorial

Calculates and outputs factorials of numbers from 0 to 16, inclusive. Factorial of a number is defined as n! = 1 * 2 * … * n.

Program output should look as follows:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000

Note that this example can be implemented in several ways:

  • using recursive factorial definition n! = n * (n-1)!
  • using multiplication of numbers from 1 to n in a loop.
  • using a built-in function of a language.

Example for versions Borland C++ Builder 6, g++ 3.4.5, Microsoft Visual C++ 6, Microsoft Visual C++ 9 (2008)

This example uses recursive factorial definition.

#include "stdio.h"

__int64 factorial(__int64 n)
{
	return ( n==0 ? 1 : n*factorial(n-1) );
}

int main(int argc, char* argv[])
{
	for (int n=0; n<=16; n++)
		printf( "%d! = %I64d\n", n, factorial(n) );
	return 0;
}

Example for versions Borland C++ Builder 6, g++ 3.4.5

This example uses recursive factorial definition.

#include <iostream>

unsigned long long factorial(unsigned long long n)
{
	if (n == 0) 
		return 1;
	else 
		return n * factorial (n - 1);
}

int main(void)
{
    for (int n = 0; n <= 16; n++) 
        std::cout << n << "! = " << factorial(n) << std::endl;
    return 0;
}

Example for versions Oracle 10g SQL

Pure SQL doesn’t support loops, recursions or user-defined functions. This example shows one possible workaround which uses

  • pseudocolumn level to construct a pseudotable containing numbers 1 through 16,
  • aggregate function sum which allows to sum the elements of a set
  • and math functions exp and ln to replace multiplication (required to calculate the factorial) with addition (provided by SQL).

Note that 0! will not be present in the return, since trying to calculate ln(0) produces an exception.

select t2.n || '! = ' || round(exp(sum(ln(t1.n))))
  from 
  ( select level n
      from dual
   connect by level <= 16) t1,
  ( select level n
      from dual
   connect by level <= 16) t2
 where t1.n<=t2.n
 group by t2.n

Example for versions gcj 3.4.5, Sun Java 6

This example uses recursive factorial definition.

public class Factorial {
    static long factorial(int n)
    {
        return ( n==0 ? 1 : n*factorial(n-1) );
    }
    public static void main(String[] args)
    {
        for (int n=0; n<=16; n++)
            System.out.println(n+"! = "+factorial(n));
    }
}

Example for versions gcj 3.4.5, Sun Java 6

This example uses iterative calculation of factorial and illustrates the use of built-in class BigInteger which allows to handle arbitrarily large integer numbers.

import java.math.BigInteger;

public class Factorial {
    public static void main(String[] args)
    {
        BigInteger f = BigInteger.ONE;
        System.out.println("0! = " + f);
        for (int n=1; n<=16; n++)
        {   f = f.multiply(BigInteger.valueOf(n));
            System.out.println( n + "! = " + f);
        }
    }
}

Example for versions Microsoft SQL Server 2005

This example uses recursive factorial definition, implemented as a recursive query — a feature included in SQL Server 2005 and higher. Each row of recursive query contains two numeric fields — n and f = n!, and each row is calculated using the data of the previous row.

with factorial(n, f) as
(
 select 0, 1
  union all
 select n+1, f*(n+1) from factorial where n<16
)
select cast(n as varchar)+'! = '+cast(f as varchar)
  from factorial

Example for versions EsCo 0.511 (Brainfuck), Müller's Brainfuck 2.0

This example uses iterative definition of factorial. Last calculated factorial is stored in variable c6 and on each step it is multiplied by next number (stored in c5). A low-level description is given in the comments, notation “cXvY” meaning that after execution of the commands in the line the data pointer is at cell X, and the value at this cell is Y. A total of 13 memory cells is used.

This example uses one minor cheat: classic Brainfuck interpreter uses byte variables to store values of memory cells, so 6! and further will cause overflow. Writing long arithmetics in Brainfuck is a bit of overkill, so in this example we assume that memory cells can store integer values. Besides, factorial length grows fast along with execution time of Brainfuck program, so the above code is limited to calculating and printing first 7 factorials.

+++++++++++++++++++++++++++++++++			c1v33 : ASCII code of !
>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++				c2v61 : ASCII code of =
>++++++++++						c3v10 : ASCII code of EOL
>+++++++						c4v7  : quantity of numbers to be calculated
>							c5v0  : current number (one digit)
>+							c6v1  : current value of factorial (up to three digits)
<<							c4    : loop counter
[							block : loop to print one line and calculate next
>++++++++++++++++++++++++++++++++++++++++++++++++.	c5    : print current number
------------------------------------------------	c5    : back from ASCII to number
<<<<.-.>.<.+						c1    : print !_=_

>>>>>							block : print c6 (preserve it)
>							c7v0  : service zero
>++++++++++						c8v10 : divizor
<<							c6    : back to dividend
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]			c6v0  : divmod algo borrowed from esolangs; results in 0 n d_n%d n%d n/d
>[<+>-]							c6    : move dividend back to c6 and clear c7
>[-]							c8v0  : clear c8

>>							block : c10 can have two digits; divide it by ten again
>++++++++++						c11v10: divizor
<							c10   : back to dividend
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]				c10v0 : another divmod algo borrowed from esolangs; results in 0 d_n%d n%d n/d
>[-]							c11v0 : clear c11
>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]c13v0 : print nonzero n/d (first digit) and clear c13
<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]] c12v0 : print nonzero n%d (second digit) and clear c12
<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]	c9v0  : print any n%d (last digit) and clear c9

<<<<<<.							c3    : EOL
>>+							c5    : increment current number
							block : multiply c6 by c5 (don't preserve c6)
>[>>+<<-]						c6v0  : move c6 to c8
>>							c8v0  : repeat c8 times
[
<<<[>+>+<<-]						c5v0  : move c5 to c6 and c7
>>[<<+>>-]						c7v0  : move c7 back to c5
>-
]
<<<<-							c4    : decrement loop counter
]

Example for versions Interactive FP

This example defines four functions — two of necessity, and two for readability. All of them accept scalar values for input; seq returns a sequence of scalars, and the other three return individual scalars.

  • zero checks whether its argument is equal to zero;
  • dec decrements its argument;
  • seq returns <0> if its argument x is equal to zero, and seq, applied to (x-1), with x appended to right otherwise (if we unwind this recursive definition, we’ll get simply the sequence of values <0 1 ... x>).
  • factorial returns 1 if its argument x is equal to zero, and factorial, applied to (x-1), multiplied by x otherwise.

The last line of the example applies factorial to each element of sequence, obtained by applying seq to 16. Note that all math operations produce floating point values, so the actual output will look like this:
< 1 1.0 2.0 6.0 24.0 120.0 720.0 5040.0 40320.0 362880.0 3628800.0 3.99168E7 4.790016E8 6.2270208E9 8.7178289E10 1.30767428E12 2.09227885E13 >

{ zero ( = @ [id, %0] ) }
{ dec ( - @ [id, %1] ) }
{ seq ( zero -> %<0> ; apndr @ [ seq @ dec , id ] ) }
{ factorial ( zero -> %1 ; * @ [id, factorial @ dec ] ) }
&factorial @ seq:16

Example for versions clisp 2.47, Corman Common Lisp 3.0, gcl 2.6.6

This example uses recursive factorial definition (which is natural for Lisp). Features:

  • math operators: (- n 1) is prefix notation equivalent to n-1 in infix notation;
  • comparison operators: (= n 0) evaluates to T if n is zero, and to nil (used as false) otherwise;
  • conditional operator if: Lisp expressions are evaluated using brackets, so they can be written in several lines;
  • function definition using defun;
  • Common Lisp macro loop;
  • format specifiers in format: ~D corresponds to printing an integer, and ~% is end-of-line.
(defun factorial (n)
  (if (= n 0)
      1
      (* n (factorial (- n 1))) ) )

(loop for i from 0 to 16
   do (format t "~D! = ~D~%" i (factorial i)) )

Example for versions Lua 5.0.3

This example uses recursive factorial definition.

function factorial(n)
    if (n == 0) then
        return 1
    else
        return n * factorial(n - 1)
    end
end

for n = 0, 16 do
    io.write(n, "! = ", factorial(n), "\n")
end

Example for versions Microsoft Visual Basic 6

This example uses iterative factorial definition. Trying to calculate 13! produces an arithmetic overflow error, so program output ends with line “12! = 479001600”. After this a message “Run-time error ‘6’: Overflow” pops up.

Option Explicit

    Declare Function AllocConsole Lib "kernel32" () As Long
    Declare Function FreeConsole Lib "kernel32" () As Long
    Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Declare Function GetStdHandle Lib "kernel32" (ByVal nStdHandle As Long) As Long
    Declare Function WriteConsole Lib "kernel32" Alias "WriteConsoleA" _
           (ByVal hConsoleOutput As Long, lpBuffer As Any, ByVal _
           nNumberOfCharsToWrite As Long, lpNumberOfCharsWritten As Long, _
           lpReserved As Any) As Long
    Declare Function Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) As Long

Private Sub Main()
    'create a console instance
    AllocConsole
    'get handle of console output
    Dim hOut As Long
    hOut = GetStdHandle(-11&)
    'output string to console output
    Dim s As String
    Dim i As Integer
    Dim f As Long
    f = 1
    s = "0! = 1" & vbCrLf
    WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
    For i = 1 To 16 Step 1
        f = f * i
        s = i & "! = " & f & vbCrLf
        WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
    Next i
    'make a pause to look at the output
    Sleep 2000
    'close the handle and destroy the console
    CloseHandle hOut
    FreeConsole
End Sub

Example for versions QBasic 1.1, QuickBASIC 4.5

This example uses recursive factorial definition.

The default data type for calculations is floating point, so program output looks like this:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 3.99168Е+07
12! = 4.790016Е+08
13! = 6.227021Е+09
14! = 8.717829Е+10
15! = 1.307674Е+12
16! = 2.092279Е+13

DECLARE FUNCTION factorial (n)

FOR i = 0 TO 16:
    PRINT STR$(i) + "! =" + STR$(factorial(i))
NEXT i
END

FUNCTION factorial (n)
    IF n = 0 THEN
        factorial = 1
    ELSE
        factorial = n * factorial(n - 1)
    END IF
END FUNCTION

Example for versions Visual Prolog 7.2

Create a new project with UI Strategy “Console” and replace contents of files main.cl and main.pro with given code.

In main.cl the only added line factorial : (integer N, integer F) procedure (i,o). specifies that factorial is a predicate of arity 2, with known first and unknown second argument. Keyword procedure describes the behavior of predicate, indicating that is will always succeed with only one solution, so no backtracking is required.

In main.pro the actual description of newly specified predicate takes place. There are two possible matches for each call of factorial — with zero or arbitrary first argument. Visual Prolog searches the clauses for matching call in the order of their appearance in the code, so if first argument is zero, it starts with first clause factorial(0,F). The first rule in this clause is !, a so-called cut, which prevents backtracking to second clause factorial(N,F) and thus ensures that there is only one solution to the call. After this the return variable F is set to 0! = 1 and the result of the clause is printed. The second clause factorial(N,F) recursively calculates F1 as factorial of N-1, assigns N*F1 to return variable F and prints the result. Finally, stdio::nl prints a new line.

When the main program runs, factorial is called exactly once, for N=12. With each call of recursion N is decremented until it reaches 0. After this factorials are returned and printed in increasing order of N. This program can process only factorials up to 12!, since trying to calculate 13! causes an integer overflow.

% main.cl
class main
    open core

predicates
    classInfo : core::classInfo.
    factorial : (integer N, integer F) procedure (i,o).
predicates
    run : core::runnable.

end class main

% main.pro
implement main
    open core

constants
    className = "main".
    classVersion = "".

clauses
    classInfo(className, classVersion).
    factorial(0,F) :- 
        !,
        F = 1, 
        stdio::write("0! = 1"),
        stdio::nl.
    factorial(N,F) :-
        factorial(N-1,F1),
        F = N*F1,
        stdio::write(N, "! = ", F),
        stdio::nl.
        
clauses
    run():-
        console::init(),
        factorial(12,F),
        programControl::sleep(1000),
        succeed().
end implement main

goal
    mainExe::run(main::run).

Example for versions gnuplot 4.2.2

This example consists of two files: factorial.gp and run.gp to emulate loop through use of load, reread and if. Built-in factorial operator ! is used. Since return of ! operator has type real, function gprintf is used to remove trailing zeros after decimal point and decimal point itself.

### factorial.gp
print a, '! = ', gprintf("%.0f", a!)
a = a + 1
if (a <= 16) reread

### run.gp
#!/usr/bin/env gnuplot
a = 0
load "factorial.gp"

Example for versions Oracle 10g SQL

This example shows the use of model clause, available since Oracle 10g. It allows array-like processing of query rows. Each row has two columns — iteration number (stored in n) and its factorial (stored in f).

select n || '! = ' || f factorial
  from dual
 model
    return all rows
    dimension by ( 0 d ) 
    measures ( 0 f, 1 n )
    rules iterate (17)
    ( f[iteration_number] = decode(iteration_number, 0, 1, f[iteration_number-1]*iteration_number),
      n[iteration_number] = iteration_number
    );

Example for versions Free Pascal 2.0.4, Free Pascal 2.2.0, gpc 20070904, Turbo Pascal 4.0, Turbo Pascal 5.0, Turbo Pascal 5.5, Turbo Pascal 6.0, Turbo Pascal 7.0

This example uses recursive factorial definition.

Note that this example works in all given implementations of Pascal, but it produces slightly different results. In gpc everything works perfectly. Turbo Pascal and Free Pascal have arithmetic overflow for factorial of numbers greater than 12, but Free Pascal reports an error:

13! = Runtime error 215 at $004013C7
$004013C7
$00401449
$004063E0

while Turbo Pascal doesn’t detect the error and simply prints wrong values:

13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184

This example doesn’t work in Turbo Pascal 3.0 and earlier due to absence of longint datatype in these versions.

program factorial;

function fact(n: integer): longint;
begin
    if (n = 0) then
        fact := 1
    else
        fact := n * fact(n - 1);
end;

var
    n: integer;

begin
    for n := 0 to 16 do
        writeln(n, '! = ', fact(n));
end.

Example for versions MySQL 3.23.57

Replace TABLE with name of any table you have access to, like mysql.help_topic.

select concat(cast(t2.n as char), "! = ",  cast(exp(sum(log(t1.n))) as char))
  from 
  ( select @i := @i+1 AS n
      from TABLE, (select @i := 0) as sel1
      limit 16 ) t1,
  ( select @j := @j+1 AS n
      from TABLE, (select @j := 0) as sel1
      limit 16 ) t2
 where t1.n <= t2.n
 group by t2.n

Example for versions Bash 3.0

This example uses recursive factorial definition.

#!/bin/bash

factorial ()
{
    local num=$1;
    if [ $num = 0 ]; then
        echo 1
        return ;
    fi;
    echo $(( $num * $(factorial $(( $num - 1 )) ) ))
}

for ((n = 0; n <= 16; n++))
do
    echo "$n! = " $(factorial $(($n)))
done

Example for versions Poplog 15.5 (Prolog)

This example consists of two parts — the first part of code should be stored in a file fact.pl placed in working folder of Poplog, and the second one has to be entered manually. [-fact]. downloads facts and rules from this file to current Prolog session (and outputs fact reconsulted to note that download succeeded). Query fact(16,X). tries to find value of X for which this predicate will evaluate to true. The output required in the example is side effect of query evaluation, and the actual result will be X = 20922789888000 ?. This means that if you’re not satisfied with this binding, you can reject it (by entering ;), and the search for better binding will continue.

% fact.pl
fact(X, F) :- 
    ( X=0, F=1; 
      Y is X-1, fact(Y, Z), F is X*Z), 
    write(X), write('! = '), write(F), nl.

% interactive
[-fact].
fact(16,X).

Example for versions Python 2.5.2

This example uses recursive factorial definition.

#! /usr/bin/env python
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

for n in range(16 + 1):
    print n, "! = ", factorial(n)

Example for versions ARIBAS 1.53

This example uses built-in factorial function.

ARIBAS uses integer type for variables by default, so type declaration can be omitted.

group(0) is used to cancel digit groups separation by underscores during output.

function fac0_16();
var n;
begin
    for n := 0 to 16 do
        writeln(n, "! = ", factorial(n): group(0));
    end;
end;

fac0_16().

Example for versions ARIBAS 1.53

This example uses recursive factorial definition.

Function name fac is used because factorial is reserved function name in ARIBAS.

ARIBAS uses integer type for variables by default, so type declaration can be omitted.

group(0) is used to cancel digit groups separation by underscores during output.

function fac(n);
begin
    if (n = 0) then
        return(1);
    end;
    return(n * fac(n - 1));
end;

function fac0_16();
var n;
begin
    for n := 0 to 16 do
        writeln(n, "! = ", fac(n): group(0));
    end;
end;

fac0_16().

Example for versions PHP 5.2.4

This example uses recursive factorial definition.

<?php
function factorial($n)
{
    if ($n == 0) {
        return 1;
    }
        
    return $n * factorial($n - 1);
}

for ($n = 0; $n <= 16; $n++) {
    echo $n . "! = " . factorial($n) . "\n";
}
?>

Example for versions Ruby 1.8.5

This example uses recursive factorial definition.

#! /usr/bin/env ruby
def factorial(n)
    if n == 0
        1
    else
        n * factorial(n - 1)
    end
end

0.upto(16) do |n|
    print(n, "! = ", factorial(n), "\n")
end

Example for versions Microsoft Visual Basic .NET 9 (2008)

This example uses recursive factorial definition.

Module Module1
    Function Factorial(ByVal n As Integer) As Long
        If n = 0 Then
            Return 1
        Else
            Return n * Factorial(n - 1)
        End If
    End Function

    Sub Main()
        For i As Integer = 0 To 16
            Console.WriteLine(i & "! = " & Factorial(i))
        Next
    End Sub
End Module

Example for versions gcc 3.4.5, gcc 3.4.5 (Objective-C), gcc 4.2.4

This example uses recursive factorial definition. Note that 13! and larger causes an overflow, so the last lines of the output look like this:

13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184

#include <stdlib.h> /* needed for EXIT_SUCCESS */
#include <stdio.h>

unsigned long long factorial(unsigned long long n)
{
    if (n == 0) {
        return 1;
    } else {
        return n * factorial (n - 1);
    }
}

int main(void)
{
    int n;
    for (n = 0; n <= 16; n++) {
        printf("%i! = %lld\n", n, factorial(n));
    }
    return EXIT_SUCCESS;
}

Example for versions gmcs 2.0.1, Microsoft Visual C# 2008

This example uses recursive factorial definition.

using System;

class Program
{
    static long Factorial(int n)
    {
        if (n == 0)
            return 1;
        else
            return n * Factorial(n - 1);
    }
    static void Main(string[] args)
    {
        for (int i = 0; i < 17; i++)
            Console.WriteLine("{0}! = {1}",i,Factorial(i));
    }
}

Example for versions Poplog 15.5 (POP-11)

This example uses recursive factorial definition. factorial(n) calculates the actual value of factorial, while loop(n) is used to loop through factorials of numbers between 0 and n, inclusive. >< is concatenation operator. Note that loop doesn’t return a value.

Alternatively, one could save function definitions to file fact.p, place it in Poplog working folder, and enter load fact.p in interactive mode to upload the contents of file.

define factorial(n);
    if n == 0 
        then 1
        else n * factorial(n - 1)
    endif
enddefine;

define loop(n);
    if n>0 
        then loop(n-1)
    endif;
    n >< '! = ' >< factorial(n) =>
enddefine;

loop(16) =>

Example for versions Perl 6 (alpha)

This version uses the reduction metaoperator to multiply every number from 1 to N (the leading [*] means “apply the * operator between each element of the following list”).

Note that the say statement could also be written as:

say "$i! = &fact($i)";

with the function call interpolated directly into the string being printed.

sub fact($n) { [*] 1..$n }

for 1..16 -> $i {
    say "$i! = ", fact($i);
}

Example for versions Euphoria v3.1.1, Euphoria v4

This example uses recursive factorial definition.

function factorial(integer n)
  atom result

  if n <= 1 then
    result =  1
  else
    result = n * factorial(n-1)
  end if

  return result
end function

for i = 0 to 16 do
 printf(1, "%d! = %d\n", {i, factorial(i)})
end for

Example for versions Euphoria v3.1.1, Euphoria v4

This example uses iterative factorial definition.

function factorial(integer n)
  atom result = 1

  if n < 1 then
    return 1
  end if

  for i = 2 to n do
    result *= i
  end for

  return result
end function

for i = 0 to 16 do
 printf(1, "%d! = %d\n", {i, factorial(i)})
end for

Example for versions Oracle 10g SQL

This example calculates factorials iteratively by means of PL/SQL.

declare
    n    number := 0;
    f    number := 1;
begin
    while (n<=16)
    loop
        dbms_output.put_line(n || '! = ' || f);
        n := n+1;
        f := f*n;
    end loop;
end;

Example for versions Squeak 3.10

This example is actually cut and paste from the Squeak core source code in the Integer class. From any Squeak image:

10000 factorial. “and press alt-p to print the result below this line”

284625968091705451890641321211986889014805140170279923079417999427441134000376444377299078675778477581588406214231752883004233994015351873905242116138271617481982419982759241828925978789812425312059465996259867065601615720360323979263287367170557419759620994797203461536981…etc… edited for brevity.

This takes about 200 milliseconds on a modern PC to compute the factorial, and about 6 seconds to convert the resulting number into a String for displaying.

The resulting number has this 35660 digits:

10000 factorial asString size

35660

factorial
	"Answer the factorial of the receiver."

	self = 0 ifTrue: [^ 1].
	self > 0 ifTrue: [^ self * (self - 1) factorial].
	self error: 'Not valid for negative integers'

Example for versions Free Pascal 2.0.4, Free Pascal 2.2.0, gpc 20070904, Turbo Pascal 1.0, Turbo Pascal 2.0, Turbo Pascal 3.0, Turbo Pascal 4.0, Turbo Pascal 5.0, Turbo Pascal 5.5, Turbo Pascal 6.0, Turbo Pascal 7.0

This example is exactly the same as main recursive example for Pascal implementations, except for that it uses real data type to store factorial values. Command writeln(f:-1:0) outputs the floating point number f with 0 digits after decimal point and left-justifies it.

program factorial;

function fact(n: integer): real;
begin
    if (n = 0) then
        fact := 1
    else
        fact := n * fact(n - 1);
end;

var
    n: integer;

begin
    for n := 0 to 16 do
        writeln(n, '! = ', fact(n):-1:0);
end.

Example for versions REXX

This example uses recursive factorial definition.

Line 3: REXX allows the numeric precision to be set arbitrarily large — as much as your memory will allow.

Line 6: String concatenation works by juxtaposing values and literals, with or without intervening spaces. If two values must be concatenated, the || operator can be used.

Line 10: The optional PROCEDURE keyword causes the routine’s variables to be local; without it they are global to the program.

The output looks as follows:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
21! = 51090942171709440000
22! = 1124000727777607680000
23! = 25852016738884976640000
24! = 620448401733239439360000
25! = 15511210043330985984000000
26! = 403291461126605635584000000
27! = 10888869450418352160768000000
28! = 304888344611713860501504000000
29! = 8841761993739701954543616000000
30! = 265252859812191058636308480000000

  1  #!/usr/bin/rexx
  2  /* Compute n! */
  3    numeric digits 40
  4
  5    do n = 0 to 30
  6      say right(n,2)"! = " right(factorial(n),35)
  7    end
  8  exit
  9
 10  factorial: procedure
 11    parse arg n .
 12
 13    if n = 0 then
 14      n = 1
 15
 16    else
 17      n = n * factorial(n - 1)
 18  return n

Example for versions D1, D2, gdc 0.24

This example uses recursive factorial definition.

module factorial;

import std.stdio;

ulong recursive(ulong x)
{
	return (x == 0 ? 1 : x * recursive( x - 1 ));
}

int main()
{
	for (int i = 0; i < 17; ++i)
	{
		writefln("%s! = %s", i, recursive(i));
	}
	return 0;
}

Example for versions j602

This example implements three methods of calculating factorial. fact represents a factorial function which generates the first n integers as an array and multiplies them together. factr represents the recursive definition. ! is the built-in factorial function.

load 'printf'

fact=: [: */ [: >: i.
factr=: 1:`(]*$:@<:)@.*

'!%d = %d' printf (,"0 fact) i.17x
'!%d = %d' printf (,"0 factr) i.17x
'!%d = %d' printf (,"0 !) i.17x

Example for versions Algol68g-1.18.0, Algol68toc-1.8

This example uses recursive factorial definition with first 7 numbers precomputed.

PROC factorial = (INT n)LONG LONG INT:
  CASE n+1 IN
    1,1,2,6,24,120,720 # a brief lookup #
  OUT
    n*factorial(n-1)
  ESAC
;

Example for versions gfortran 4.5.0, Intel Visual Fortran 11.1

This example uses iterative factorial definition. Format specifiers I and A are used for printing integers and strings, respectively. Trying to calculate 13! produces an arithmetic overflow error, so last lines of program output look like this:

13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184

    program Factorial

    integer :: f,n

    f = 1
    n = 0
    
    do
        print '(I2, A, I10)', n, "! = ", f
        n = n + 1
        f = f * n
        if (n==17) then
            exit
        end if
    end do

    end program Factorial

Example for versions OCaml 3.11

This example uses an auxiliary function so that tail recursion is possible.

let factorial n =
    aux n 1;;

let rec aux n accum =
    if n = 1 then accum
    else aux (n-1) (accum*n);;

Example for versions OCaml 3.11

This example shows the naive way to implement the factorial function. However, it is not tail recursive, since the recursive function call is not the only statement on the line.

let rec factorial n =
    if n = 1 then 1
    else factorial (n-1) * n;;

Example for versions SpiderMonkey (Firefox 3.5)

This example uses recursive factorial definition and is meant to be executed from the web-browser. To run the example, copy its source text to a file factorial.js and create an HTML file placed in the same directory and containing the following text:

<head><script type="text/javascript" src="factorial.js"></script></head> <body></body>

When you open the HTML file, JavaScript code runs and writes its output to the page shown. document.clear() command clears everything that is written on the currrent web-page.

function factorial(n)
{   if (n == 0)
        return 1;
    else
        return n * factorial(n-1);
}
var i;
document.clear();
for (i = 0; i <= 16; i++)
    document.write(i + "! = " + factorial(i) + "<br />");

Example for versions GHC 6.10.4

This example uses recursive factorial definition and consists of three major parts:

  • definition of factorial function, which takes one argument of Integer type (integer number of unlimited precision) and returns the same type. The function is defined recursively, and types of argument and return are given explicitly to avoid ambiguity.
  • definition of line function, which prints the number and its factorial in required format. Use of
    printf command is the same as in C++.
  • printing the numbers and their factorials themselves. [0..16] creates a list of numbers from 0 to 16, inclusive. Function map applies first argument (line function) to each element of second argument ([0..16] list) and as a result creates a list of so-called “output actions” (which can be used as values in Haskell). To combine these actions in one we use sequence_ command, which is applied to a list of actions, executes first action from the list and recursively applies it to the tail of the list. But for simplicity, we use mapM_, which combines map and sequence_.
module Main where

import Text.Printf

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

line x = printf "%d! = %d\n" x $ factorial x

main = mapM_ line [0..16]

Example for versions Corman Common Lisp 3.0, gcl 2.6.6

In this example the inner loop with collect clause produces a list of numbers from 1 to n. After this operation * is applied to this list, and the product of the numbers is printed.

(loop for n from 0 to 16
   do (format t "~D! = ~D~%" n 
        (apply '* (loop for i from 1 to n 
                        collect i)) ) )

Example for versions Furry Paws

This example works in exactly the same way as the one in Interactive FP, except for that it doesn’t define zero function, since it’s built-in. Note that here all operations are done within integer data type, and 13! overflows it, so the program can be called only to print factorials up to 12!. show is another way to output data.

dec = sub.[id, ~1]
seq = zero -> [id] ; cat.[seq.dec, [id]]
factorial = zero -> ~1 ; mul.[id, factorial.dec]

main = show.(return @factorial.(seq.~12))

Example for versions gnat 3.4.5, gnat 4.3.2

This example uses recursive factorial definition.

Note that there are different packages for printing text, integers and long integers. put command generally accepts several arguments: Item is the number/string to print, Width is the number of positions to use, Fore and Aft are the numbers of decimal digits to be printed before and after decimal separator etc. If there is only one argument, it is considered to be Item. Setting Width to a number which is less than the actual length of the number prints it without leading spaces (which is the default for Ada).

Another thing to note is that Ada doesn’t support implicit data type conversions, so to calculate N*Fact(N-1) one has to convert N to Long_Long_Integer explicitly first.

with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Long_Long_Integer_Text_IO;

procedure Factorial is
begin
   declare 
      function Fact (N: Integer) return Long_Long_Integer is
      begin
         if N=0 then
            return 1;
         else 
            return Long_Long_Integer(N)*Fact(N-1);
         end if;
      end Fact;
   i: Integer := 0;
   begin
      loop
         Ada.Integer_Text_IO.Put (Item => i, Width => 1);
         Ada.Text_IO.Put ("! = ");
         Ada.Long_Long_Integer_Text_IO.Put (Item => Fact(i), Width => 1);
         Ada.Text_IO.New_Line;
         i := i + 1;
         exit when i=17;
      end loop;
   end;
end Factorial;

Example for versions Scratch 1.4

Since Scratch is a graphical language, the print-screen contains the actual information about the program, source text is only a transcription.

strs is a vector-style array. delete all block is required to clean it before running program again. repeat is a kind of loop which repeats its body for exactly the given number of times. join is a block which concatenates its arguments. hide hides the avatar (to clean the stage).

Scratch doesn’t have a standard output as such, neither has it a possibility of “saying” multi-line things. An array was used to output the example results in the required form.

delete all of strs
set i to 0
set f to 1
repeat 17
   add (join i (join (! = ) f)) to strs
   set i to (i + 1)
   set f to (f * i)
hide

Factorial example in Scratch
Factorial example in Scratch

Example for versions UCBLogo 6.0

This example uses recursive factorial definition. It defines two functions — factorial which calculates N! and print_factorial which loops through numbers from i to N and outputs their factorials.

to factorial :N
   ifelse :N = 0 [output 1] [output :N * factorial :N - 1]
end

to print_factorial :i :N
   repeat :N - :i + 1 [(print :i [! =] factorial :i)
                       make "i sum :i 1]
end

print_factorial 0 16

Example for versions Go gc

The example implements both recursive and iterative methods of calculating factorial and a generic function for printing the results of using any of the methods.

package main
import "fmt"

//Recursive Factorial
func factr(n uint64) uint64 {
    if (n < 2) { return 1 }
    return n * factr(n-1)
}

//Iterative Factorial
func facti(n uint64) uint64 {
    var ret uint64 = 1
    for ; n > 0; n-- {
        ret *= n
    }
    return ret
}

func printFact(fact func(uint64) uint64) {
    for i := 0; i < 17; i++ {
        fmt.Printf("!%d = %d\n", i, fact(uint64(i)))
    }
}

func main() {
    printFact(factr)
    fmt.Println("--")
    printFact(facti)
}

Example for versions Ruby 1.8.5

This example uses an iterative factorial definition.

def fact(n)
  (1..n).inject(1) {|a,b| a*b}
end

(0..16).each {|x| puts "#{x}! = #{fact(x)}"}

Example for versions D1, D2, gdc 0.24

This example uses iterative factorial definition.

module factorial;

import std.stdio;

ulong iterative(ulong x)
{
	ulong result = 1;
	
	for (ulong count = 1; count <= x; ++count)
	{
		result *= count;
	}
	return result;
}

int main()
{
	for (int i = 0; i < 17; ++i)
	{
		writefln("%s! = %s", i, iterative(i));
	}
	return 0;
}

Example for versions Scala 2.7.7-final

This example uses recursive factorial definition.

object Factorial {
    def factorial(n: Int): Long = 
        if (n == 0) 1 
               else n * factorial(n - 1)
    def main(args: Array[String]) {
        for {i <- List.range(0, 17)} 
            yield { println(i + "! = " + factorial(i)) }
    }
}

Example for versions Scala 2.7.7-final

This example uses iterative factorial definition.

object Factorial {
    def main(args: Array[String]) {
        var f = BigInt(1)
        format("0! = %s\n", f)
        for {i <- 1 to 16} {
             f *= i;
             format("%s! = %s\n", i, f)
        }
    }
}

Example for versions gawk 3.1.6, mawk 1.3.3

This example uses iterative factorial definition. Individual statements within code block can be separated with semicolons (;) or new lines.

BEGIN {
    f = 1
    print "0! = " f
    for (i=1; i<17; i++) {
        f *= i
        print i "! = " f
    }
}

Example for versions GHC 6.10.4

This example uses the Prelude function product, which computes the product of a list of numbers. When the list is empty, it returns 1 (the multiplicative identity), so this works for 0 too.

module Main where

factorial :: Integer -> Integer
factorial n = product [1..n]

line x = putStrLn $ show x ++ "! = " ++ factorial x

main = mapM_ line [0..16]

Example for versions GHC 6.10.4

This example performs a “fold” using the function foldl (which is a left-fold, but since multiplication is associative, left fold and right fold are the same) to fold multiplication over the list [1..n]. We provide the “initial value” 1, so that it will produce 1 when the list is empty.

module Main where

factorial :: Integer -> Integer
factorial n = foldl (*) 1 [1..n]

line x = putStrLn $ show x ++ "! = " ++ factorial x

main = mapM_ line [0..16]

Example for versions perl 5.8.8

This example uses the reduce function from the List::Util module. Note that we have to put an extra 1 in the beginning, so that it will work when 1 .. $n is empty (i.e. when $n is 0).

use List::Util qw(reduce);
sub fact {
  my $n = shift;
  reduce { $a * $b } 1, 1 .. $n
}

foreach my $i (1..16) {
    print "$i! = ", fact($i), "\n";
}

Example for versions perl 5.8.8

sub fact {
  my $n = shift;
  $n == 0 ? 1 : $n*fact($n-1);
}

foreach my $i (1..16) {
    print "$i! = ", fact($i), "\n";
}

Example for versions perl 5.8.8

sub fact {
  my $n = shift;
  my $result = 1;
  foreach my $i (1 .. $n) {
    $result *= $i;
  }
  $result
}

foreach my $i (1..16) {
    print "$i! = ", fact($i), "\n";
}

Example for versions S-lang 2.2.2

This example uses recursive factorial definition and features the usage of recursive functions in S-lang. To create a recursive function, you have first to declare it without listing parameters or implementation — define factorial ();, and then actually define it, with the list of parameters and function body.

Another feature included in this example is usage of $ suffix. A string literal can end with a suffix which defines the way of processing this string. $ suffix requires that variable name substitution is performed on the string before using it. This means that each variable name prefixed by $ character within the string will be replaced with variable value. Variable name can be enclosed in {} braces to separate it from the string contents; the braces can be omitted if variable name is followed by a space.

Note that the default numeric data type in S-lang is integer, so the given example produces overflow error when calculating 13!.

define factorial ();

define factorial (n)
{   if (n==0) return 1;
     return n * factorial (n-1);
};

for (i=0; i<17; i++)
{   f = factorial (i);
    message ("${i}! = ${f}"$);
};

Example for versions S-lang 2.2.2

This example shows array operations in S-lang. [1:i] creates a list of numbers from 1 to i; note that the default data type for array operations is double even if the numbers are integer. Intrinsic function prod (since version 2.1) returns the product of elements of its parameter. Intrinsic function sprintf provides C-style printing, %.0f printing floating point number with zero digits after decimal comma.

for (i=0; i<17; i++)
    sprintf ("%d! = %.0f", i, prod ( [1:i] ) );

Example for versions Sanscript 2.2

Sanscript is a fully visual programming language, so no source code is available. See screeshots instead.

First screenshot shows the flowgram of the example. The main part of it is “Repeat” function (an analogue of loop in other languages) which calculates the factorials of numbers from 1 to 16 and stores them in a list. This function has two inlet/outlet pairs which correspond to global variables in other languages: factorial and message. factorial is an integer which stores the current value of factorial. message is a list of text lines n! = (n!). The “Repeat” function has one more inlet N which defines the number of iterations to be done. The inlets are initialized with constants and an empty list, and the loop starts. Once the calculations are done, message has to be displayed. This can be done using Write List as Text function, which writes all elements of list into a single text variable. The separator between elements of the list is defined with sep inlet; in this case it is newline character, generated using “Char” function which converts an ASCII-code into a corresponding character. Finally, the concatenated list is displayed using “Display Message” function.

Second screenshot shows the intrinsics of “Repeat” function. Element marked with “1, 2 …” is loop counter, started with 1 and incremented by 1 each iteration. On each iteration factorial is multiplied by the value of loop counter (using “Times” function). After this its new value is concatenated with loop counter and “! = ” constant string (using “Append Text” function) to produce one line of output. Finally, this line is added to the list message (using “Add Last Item”) function.

Factorial example in Sanscript (flowgram)
Factorial example in Sanscript (flowgram)

Factorial example in Sanscript (repeat)
Factorial example in Sanscript (repeat)

Example for versions Ruby 1.9

This example uses an iterative factorial definition

def fact(n)
  (1..n).reduce(:*)
end

(0..16).each {|x| puts "#{x}! = #{fact(x)}"}

Example for versions Simply Scala

This examples shows how to define ! as a method applied to Int.

def factorial(n: Int): BigInt = 
    if (n == 0) 1 
           else factorial(n - 1) * n
class Factorizer(n: Int) {
    def ! = factorial(n)
}
implicit def int2fact(n: Int) = new Factorizer(n);	

for {i <- List.range(0, 17)} 
    println(i + "! = " + (i!))

Example for versions Roco 20071014

This example uses iterative definition of factorial. Cell [0] stores the current number, cell [1] is temporary, and cell [2] stores factorial of current number.

co calc{
/* break the loop when the counter is 17 - the number for which we don't need factorial */
eq [1] [0] 17
if [1] ac

/* output current factorial */
iout [0]
cout 33
cout 32
cout 61
cout 32
iout [2]
cout 13
cout 10

/* calculate next number and store it to [2]*/
add [0] [0] 1
mul [2] [2] [0]
}

/* initialize with 0! = 1 */
set [0] 0
set [2] 1

ca calc

ac

Example for versions fsharp 2.0.0

This example uses recursive definition of factorial, expressed in procedural paradigm.

factorial defines the actual factorial-calculating routine, and printFact defines the routine that outputs calculated factorials in required format.

let rec factorial n =
    match n with
    | 0 -> 1
    | _ -> n * factorial (n - 1)

let rec printFact n  =
    match n with 
    | 0 -> printfn "0! = 1"
    | _ -> printFact (n-1)
           printfn "%d! = %d"  n (factorial (n))
           
printFact(16)