Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Factorial

From Rosetta Code
Task
Factorial
You are encouraged tosolve this task according to the task description, using any language you may know.
Definitions
  •   The factorial of  0   (zero)   isdefined as being   1   (unity).
  •   The  Factorial Function   of a positive integer,  n,   is defined as the product of the sequence:
n,  n-1,  n-2,   ...   1


Task

Write a function to return the factorial of a number.

Solutions can be iterative or recursive.

Support for trapping negative  n   errors is optional.


Related task



0815

This is an iterative solution which outputs the factorial of each number supplied on standard input.

}:r:        Start reader loop.  |~      Read n,    #:end:    if n is 0 terminates  >=        enqueue it as the initial product, reposition.  }:f:      Start factorial loop.    x<:1:x- Decrement n.    {=*>    Dequeue product, position n, multiply, update product.  ^:f:  {+%       Dequeue incidental 0, add to get Y into Z, output fac(n).  <:a:~$    Output a newline.^:r:
Output:
seq 6 | 0815 fac.012618782d0

11l

F factorial(n)   V result = 1   L(i) 2..n      result *= i   R resultL(n) 0..5   print(n‘ ’factorial(n))
Output:
0 11 12 23 64 245 120

360 Assembly

For maximum compatibility, this program uses only the basic instruction set.

FACTO    CSECT         USING  FACTO,R13SAVEAREA B      STM-SAVEAREA(R15)         DC     17F'0'         DC     CL8'FACTO'STM      STM    R14,R12,12(R13)         ST     R13,4(R15)         ST     R15,8(R13)         LR     R13,R15         base register and savearea pointer         ZAP    N,=P'1'         n=1LOOPN    CP     N,NN            if n>nn         BH     ENDLOOPN        then goto endloop         LA     R1,PARMLIST         L      R15,=A(FACT)         BALR   R14,R15         call fact(n)         ZAP    F,0(L'R,R1)     f=fact(n)DUMP     EQU    *         MVC    S,MASK         ED     S,N         MVC    WTOBUF+5(2),S+30         MVC    S,MASK         ED     S,F         MVC    WTOBUF+9(32),S         WTO    MF=(E,WTOMSG)           AP     N,=P'1'         n=n+1           B      LOOPNENDLOOPN EQU    *RETURN   EQU    *         L      R13,4(0,R13)         LM     R14,R12,12(R13)         XR     R15,R15         BR     R14FACT     EQU    *               function FACT(l)         L      R2,0(R1)         L      R3,12(R2)         ZAP    L,0(L'N,R2)     l=n         ZAP    R,=P'1'         r=1         ZAP    I,=P'2'         i=2LOOP     CP     I,L             if i>l         BH     ENDLOOP         then goto endloop         MP     R,I             r=r*i         AP     I,=P'1'         i=i+1           B      LOOPENDLOOP  EQU    *         LA     R1,R            return r         BR     R14             end function FACT         DS     0DNN       DC     PL16'29'N        DS     PL16F        DS     PL16C        DS     CL16II       DS     PL16PARMLIST DC     A(N)S        DS     CL33            MASK     DC     X'40',29X'20',X'212060'  CL33WTOMSG   DS     0F         DC     H'80',XL2'0000'WTOBUF   DC     CL80'FACT(..)=................................ 'L        DS     PL16R        DS     PL16I        DS     PL16         LTORG         YREGS           END    FACTO
Output:
FACT(29)= 8841761993739701954543616000000

68000 Assembly

This implementation takes a 16-bit parameter as input and outputs a 32-bit product. It does not trap overflow from0xFFFFFFFF to 0, and treats both input and output as unsigned.

Factorial:;input: D0.W: number you wish to get the factorial of.;output: D0.LCMP.W#0,D0BEQ.isZeroCMP.W#1,D0BEQ.isOneMOVEM.LD4-D5,-(SP)MOVE.WD0,D4MOVE.WD0,D5SUBQ.W#2,D5;D2 = LOOP COUNTER.;Since DBRA stops at FFFF we can't use it as our multiplier.;If we did, we'd always return 0!.loop:SUBQ.L#1,D4MOVE.LD1,-(SP)MOVE.LD4,D1JSRMULU_48;multiplies D0.L by D1.WEXGD0,D1;output is in D1 so we need to put it in D0MOVE.L(SP)+,D1DBRAD5,.loopMOVEM.L(SP)+,D4-D5RTS.isZero:.isOne:MOVEQ#1,D0RTSMULU_48:;"48-BIT" MULTIPLICATION.;OUTPUTS HIGH LONG IN D0, LOW LONG IN D1;INPUT: D0.L, D1.W = FACTORSMOVEM.LD2-D7,-(SP)SWAPD1CLR.WD1SWAPD1;CLEAR THE TOP WORD OF D1.MOVE.LD1,D2EXGD0,D1;D1 IS OUR BASE VALUE, WE'LL USE BIT SHIFTS TO REPEATEDLY MULTIPLY.MOVEQ#0,D0;CLEAR UPPER LONG OF PRODUCTMOVE.LD1,D3;BACKUP OF "D1" (WHICH USED TO BE D0);EXAMPLE: $40000000*$225 = ($40000000 << 9) + ($40000000 << 5) + ($40000000 << 2) + $40000000;FACTOR OUT AS MANY POWERS OF 2 AS POSSIBLE.MOVEQ#0,D0LSR.L#1,D2BCS.wasOdd;if odd, leave D1 alone. Otherwise, clear it. This is our +1 for an odd second operand.MOVEQ#0,D1.wasOdd:MOVEQ#31-1,D6;30 BITS TO CHECKMOVEQ#1-1,D7;START AT BIT 1, MINUS 1 IS FOR DBRA CORRECTION FACTOR.shiftloop:LSR.L#1,D2BCC.noShiftMOVE.WD7,-(SP)MOVEQ#0,D4MOVE.LD3,D5.innershiftloop:ANDI#%00001111,CCR       ;clear extend flagROXL.LD5ROXL.LD4DBRAD7,.innershiftloopANDI#%00001111,CCRADDX.LD5,D1ADDX.LD4,D0MOVE.W(SP)+,D7.noShift:addq.l#1,d7dbrad6,.shiftloopMOVEM.L(SP)+,D2-D7RTS
Output:

10! = 0x375F00 or 3,628,800

AArch64 Assembly

Works with:as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B *//*  program factorial64.s   *//*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" /*********************************//* Initialized data              *//*********************************/.dataszMessLargeNumber:   .asciz "Number N to large. \n"szMessNegNumber:     .asciz "Number N is negative. \n" szMessResult:        .asciz "Resultat =  @ \n"      // message result/*********************************//* UnInitialized data            *//*********************************/.bss sZoneConv:         .skip 24/*********************************//*  code section                 *//*********************************/.text.global main main:                      // entry of program      mov x0,#-5    bl factorial    mov x0,#10    bl factorial    mov x0,#20    bl factorial    mov x0,#30    bl factorial 100:                      // standard end of the program     mov x0,0              // return code    mov x8,EXIT           // request to exit program    svc 0                 // perform the system call /********************************************//*     calculation                         *//********************************************//* x0 contains number N */factorial:    stp x1,lr,[sp,-16]!            // save  registers    cmp x0,#0    blt 99f    beq 100f    cmp x0,#1    beq 100f    bl calFactorial    cmp x0,#-1                      // overflow ?    beq 98f    ldr x1,qAdrsZoneConv    bl conversion10    ldr x0,qAdrszMessResult    ldr x1,qAdrsZoneConv    bl strInsertAtCharInc          // insert result at @ character    bl affichageMess               // display message    b 100f 98:                               // display error message    ldr x0,qAdrszMessLargeNumber    bl affichageMess    b 100f99:                               // display error message    ldr x0,qAdrszMessNegNumber    bl affichageMess 100:    ldp x1,lr,[sp],16             // restaur  2 registers    ret                           // return to address lr x30qAdrszMessNegNumber:       .quad szMessNegNumberqAdrszMessLargeNumber:     .quad szMessLargeNumberqAdrsZoneConv:             .quad sZoneConvqAdrszMessResult:          .quad szMessResult/******************************************************************//*     calculation                         */ /******************************************************************//* x0 contains the number N */calFactorial:    cmp x0,1                // N = 1 ?    beq 100f                // yes -> return     stp x20,lr,[sp,-16]!    // save  registers    mov x20,x0              // save N in x20    sub x0,x0,1             // call function with N - 1    bl calFactorial    cmp x0,-1               // error overflow ?    beq 99f                 // yes -> return    mul x10,x20,x0          // multiply result by N     umulh x11,x20,x0        // x11 is the hi rd  if <> 0 overflow    cmp x11,0    mov x11,-1              // if overflow  -1 -> x0    csel x0,x10,x11,eq      // else x0 = x1099:    ldp x20,lr,[sp],16      // restaur  2 registers100:    ret                     // return to address lr x30/********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"
Output:
Number N is negative.Resultat =  3628800Resultat =  2432902008176640000Number N to large.

ABAP

Iterative

formfactorialusingiv_valtypei.data:lv_restypeivalue1.doiv_valtimes.multiplylv_resbysy-index.enddo.iv_val=lv_res.endform.

Recursive

formfac_recusingiv_valtypei.data:lv_temptypei.ifiv_val=0.iv_val=1.else.lv_temp=iv_val-1.performfac_recusinglv_temp.multiplyiv_valbylv_temp.endif.endform.

Acornsoft Lisp

Recursive

(defunfactorial(n)(cond((zeropn)1)(t(timesn(factorial(sub1n))))))

Iterative

(defunfactorial(n(result.1))(loop(until(zeropn)result)(setqresult(timesnresult))(setqn(sub1n))))

Action!

Action! language does not support recursion. Another limitation are integer variables of size up to 16-bit.

CARD FUNC Factorial(INT n BYTE POINTER err)  CARD i,res  IF n<0 THEN    err^=1 RETURN (0)  ELSEIF n>8 THEN    err^=2 RETURN (0)  FI      res=1  FOR i=2 TO n  DO     res=res*i  OD      err^=0RETURN (res)PROC Main()  INT i,f  BYTE err  FOR i=-2 TO 10  DO     f=Factorial(i,@err)    IF err=0 THEN      PrintF("%I!=%U%E",i,f)    ELSEIF err=1 THEN      PrintF("%I is negative value%E",i)    ELSE      PrintF("%I! is to big%E",i)    FI  ODRETURN
Output:

Screenshot from Atari 8-bit computer

-2 is negative value-1 is negative value0!=11!=12!=23!=64!=245!=1206!=7207!=50408!=403209! is to big10! is to big

ActionScript

Iterative

publicstaticfunctionfactorial(n:int):int{if(n<0)return0;varfact:int=1;for(vari:int=1;i<=n;i++)fact*=i;returnfact;}

Recursive

publicstaticfunctionfactorial(n:int):int{if(n<0)return0;if(n==0)return1;returnn*factorial(n-1);}

Ada

Iterative

functionFactorial(N:Positive)returnPositiveisResult:Positive:=N;Counter:Natural:=N-1;beginforIinreverse1..CounterloopResult:=Result*I;endloop;returnResult;endFactorial;

Recursive

functionFactorial(N:Positive)returnPositiveisResult:Positive:=1;beginifN>1thenResult:=N*Factorial(N-1);endif;returnResult;endFactorial;

Numerical Approximation

withAda.Numerics.Generic_Complex_Types;withAda.Numerics.Generic_Complex_Elementary_Functions;withAda.Numerics.Generic_Elementary_Functions;withAda.Text_IO.Complex_Io;withAda.Text_Io;useAda.Text_Io;procedureFactorial_Numeric_ApproximationistypeRealisdigits15;packageComplex_Pckis newAda.Numerics.Generic_Complex_Types(Real);useComplex_Pck;packageComplex_Iois newAda.Text_Io.Complex_Io(Complex_Pck);useComplex_IO;packageCmplx_Elem_Funcsis newAda.Numerics.Generic_Complex_Elementary_Functions(Complex_Pck);useCmplx_Elem_Funcs;functionGamma(X:Complex)returnComplexispackageElem_Funcsis newAda.Numerics.Generic_Elementary_Functions(Real);useElem_Funcs;useAda.Numerics;-- Coefficients used by the GNU Scientific LibraryG:Natural:=7;P:constantarray(Naturalrange0..G+1)ofReal:=(0.99999999999980993,676.5203681218851,-1259.1392167224028,771.32342877765313,-176.61502916214059,12.507343278686905,-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7);Z:Complex:=X;Cx:Complex;Ct:Complex;beginifRe(Z)<0.5thenreturnPi/(Sin(Pi*Z)*Gamma(1.0-Z));elseZ:=Z-1.0;Set_Re(Cx,P(0));Set_Im(Cx,0.0);forIin1..P'LastloopCx:=Cx+(P(I)/(Z+Real(I)));endloop;Ct:=Z+Real(G)+0.5;returnSqrt(2.0*Pi)*Ct**(Z+0.5)*Exp(-Ct)*Cx;endif;endGamma;functionFactorial(N:Complex)returnComplexisbeginreturnGamma(N+1.0);endFactorial;Arg:Complex;beginPut("factorial(-0.5)**2.0 = ");Set_Re(Arg,-0.5);Set_Im(Arg,0.0);Put(Item=>Factorial(Arg)**2.0,Fore=>1,Aft=>8,Exp=>0);New_Line;forIin0..9loopSet_Re(Arg,Real(I));Set_Im(Arg,0.0);Put("factorial("&Integer'Image(I)&") = ");Put(Item=>Factorial(Arg),Fore=>6,Aft=>8,Exp=>0);New_Line;endloop;endFactorial_Numeric_Approximation;
Output:
factorial(-0.5)**2.0 = (3.14159265,0.00000000)factorial( 0) = (     1.00000000,     0.00000000)factorial( 1) = (     1.00000000,     0.00000000)factorial( 2) = (     2.00000000,     0.00000000)factorial( 3) = (     6.00000000,     0.00000000)factorial( 4) = (    24.00000000,     0.00000000)factorial( 5) = (   120.00000000,     0.00000000)factorial( 6) = (   720.00000000,     0.00000000)factorial( 7) = (  5040.00000000,     0.00000000)factorial( 8) = ( 40320.00000000,     0.00000000)factorial( 9) = (362880.00000000,     0.00000000)

Agda

moduleFactorialwhereopenimportData.Natusing(;zero;suc;_*_)factorial:(n:)ℕfactorialzero=1factorial(sucn)=(sucn)*(factorialn)

Agena

Tested with Agena 5.1.5 Win32

scope  # factorials using the arbitrary precision mapm library    import mapm; # explicit import needed for: Linux, Mac OS X, Windows and Solaris    mapm.xdigits( 100 );        # need to set the precision - 100 is enough for 60!    # computes factorial n iteratively, using mapm    local constant factorial := proc( n :: number ) :: xnumber        if n < 2 then return mapm.xnumber( 1 )        else            local f := mapm.xnumber( 2 );            for i from 3 to n do f := f * i od;            return f        fi    end;    # returns a string representation of the integer portion of an xnumber    local constant asstring := proc( n :: xnumber ) :: string        local constant str   := mapm.xtostring( n );        local constant point := "." in str;        return if point <> null then str[ 1 to point - 1 ] else str fi;    end;    for t from  0 to 9 do printf( "%2d! is %d\n", t, mapm.xtonumber( factorial( t ) ) ) od;    for t from 10 to 60 by 10 do printf( "%2d! is %s\n", t, asstring( factorial( t ) ) ) od;end
Output:
 0! is 1 1! is 1 2! is 2 3! is 6 4! is 24 5! is 120 6! is 720 7! is 5040 8! is 40320 9! is 36288010! is 362880020! is 243290200817664000030! is 26525285981219105863630848000000040! is 81591528324789773434561126959611589427200000000050! is 3041409320171337804361260816606476884437764156896051200000000000060! is 8320987112741390144276341183223364380754172606361245952449277696409600000000000000

Aime

Iterative

integerfactorial(integer n){    integer i, result;    result = 1;    i = 1;    while (i < n) {        i += 1;        result *= i;    }    return result;}

ALGOL 60

Works with:A60
begincomment factorial - algol 60;integerprocedure factorial(n);integer n;begininteger i,fact;               fact:=1;for i:=2step 1until ndo                       fact:=fact*i;               factorial:=factend;integer i;for i:=1step 1until 10do outinteger(1,factorial(i));       outstring(1,"\n")end
Output:
 1  2  6  24  120  720  5040  40320  362880  3628800

ALGOL 68

Iterative

PROC factorial = (INT upb n)LONGLONGINT:(LONGLONGINT z := 1;FOR nTO upb nDO z *:= nOD;  z); ~

Numerical Approximation

Works with:ALGOL 68 version Revision 1 - no extensions to language used
Works with:ALGOL 68G version Any - tested with release1.18.0-9h.tiny
INT g = 7;[]REAL p = []REAL(0.99999999999980993, 676.5203681218851,   -1259.1392167224028,                771.32342877765313,   -176.61502916214059,     12.507343278686905,                 -0.13857109526572012,   9.9843695780195716e-6, 1.5056327351493116e-7)[@0];PROC complex gamma = (COMPL in z)COMPL: (# Reflection formula #COMPL z := in z;IF reOF z < 0.5THEN    pi / (complex sin(pi*z)*complex gamma(1-z))ELSE    z -:= 1;COMPL x := p[0];FOR iTO g+1DO x +:= p[i]/(z+i)OD;COMPL t := z + g + 0.5;    complex sqrt(2*pi) * t**(z+0.5) * complex exp(-t) * xFI);OP ** = (COMPL z, p)COMPL: ( z=0|0|complex exp(complex ln(z)*p) );PROC factorial = (COMPL n)COMPL: complex gamma(n+1);FORMAT compl fmt = $g(-16, 8)"⊥"g(-10, 8)$;test:(  printf(($q"factorial(-0.5)**2="f(compl fmt)l$, factorial(-0.5)**2));FOR iTO 9DO    printf(($q"factorial("d")="f(compl fmt)l$, i, factorial(i)))OD)
Output:
 factorial(-0.5)**2=      3.14159265⊥0.00000000 factorial(1)=      1.00000000⊥0.00000000 factorial(2)=      2.00000000⊥0.00000000 factorial(3)=      6.00000000⊥0.00000000 factorial(4)=     24.00000000⊥0.00000000 factorial(5)=    120.00000000⊥0.00000000 factorial(6)=    720.00000000⊥0.00000000 factorial(7)=   5040.00000000⊥0.00000000 factorial(8)=  40320.00000000⊥0.00000000 factorial(9)= 362880.00000000⊥0.00000000

Recursive

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

ALGOL W

Iterative solution

begin% computes factorial n iteratively                                       %integerprocedure factorial(integervalue n ) ;if n < 2then 1elsebegininteger f;            f := 2;for i := 3until ndo f := f * i;            fend factorial ;for t := 0until 10do write( "factorial: ", t, factorial( t ) );end.

ALGOL-M

INTEGER FUNCTION FACTORIAL( N ); INTEGER N;BEGIN    INTEGER I, FACT;    FACT := 1;    FOR I := 2 STEP 1 UNTIL N DO        FACT := FACT * I;    FACTORIAL := FACT;END;

AmigaE

Recursive solution:

PROC fact(x) IS IF x>=2 THEN x*fact(x-1) ELSE 1PROC main()  WriteF('5! = \d\n', fact(5))ENDPROC

Iterative:

PROC fact(x)  DEF r, y  IF x < 2 THEN RETURN 1  r := 1; y := x;  FOR x := 2 TO y DO r := r * xENDPROC r

AntLang

AntLang is a functional language, but it isn't made for recursion - it's made for list processing.

factorial:{1 */ 1+range[x]} /Call: factorial[1000]

Apex

Iterative

public static long fact(final Integer n) {    if (n < 0) {        System.debug('No negative numbers');        return 0;    }    long ans = 1;    for (Integer i = 1; i <= n; i++) {        ans *= i;    }    return ans;}

Recursive

public static long factRec(final Integer n) {    if (n < 0){        System.debug('No negative numbers');        return 0;    }    return (n < 2) ? 1 : n * fact(n - 1);}

APL

Both GNU APL and the DYALOG dialect of APL provides a factorial function:

!6720

But, if we want to reimplement it, we can start by noting thatn! is found by multiplying together a vector of integers 1, 2...n. This definition ('multiply'—'together'—'integers from 1 to'—'n') can be expressed directly in APL notation:

FACTORIAL{×/}⍝ OR:   FACTORIAL←×/⍳

And the resulting function can then be used instead of the (admittedly more convenient) builtin one:

FACTORIAL6720
Works with:Dyalog APL

A recursive definition is also possible:

fac{>1:×fac-11}fac5120

Apple

 > [(*)/ₒ 1 (⍳ 1 x 1)] 75040

In theory, this generates an array starting at 1 and then folds with (*). But this is optimized into a single loop with no allocations—we can verify that deforestation ocurred by inspecting the generated assembly:

 > :asm [(*)/ₒ 1 (⍳ 1 x 1)]    mov x6, x0    mov x0, #0x1    mov x2, #0x1    eor x1, x1, x1    cmp x1, x6    b.GE apple_1apple_0:    mul x0, x0, x2    add x2, x2, #0x1    add x1, x1, #0x1    cmp x1, x6    b.LT apple_0apple_1:    ret

AppleScript

Iteration

onfactorial(x)ifx<0thenreturn0setRto1repeatwhilex>1set{R,x}to{R*x,x-1}endrepeatreturnRendfactorial

Recursion

Curiously, this recursive version executes a little faster than the iterative version above. (Perhaps because the iterative code is making use of list splats)

-- factorial :: Int -> Intonfactorial(x)ifx>1thenx*(factorial(x-1))else1endifendfactorial

Fold

We can also define factorial asproduct(enumFromTo(1, x)), where product is defined in terms of a fold.

------------------------ FACTORIAL ------------------------- factorial :: Int -> Intonfactorial(x)product(enumFromTo(1,x))endfactorial--------------------------- TEST -------------------------onrunfactorial(11)--> 39916800endrun-------------------- GENERIC FUNCTIONS --------------------- enumFromTo :: Int -> Int -> [Int]onenumFromTo(m,n)ifmnthensetxsto{}repeatwithifrommtonsetendofxstoiendrepeatxselse{}endifendenumFromTo-- foldl :: (a -> b -> a) -> a -> [b] -> aonfoldl(f,startValue,xs)tellmReturn(f)setvtostartValuesetlngtolengthofxsrepeatwithifrom1tolngsetvto|λ|(v,itemiofxs,i,xs)endrepeatreturnvendtellendfoldl-- Lift 2nd class handler function into 1st class script wrapper-- mReturn :: Handler -> ScriptonmReturn(f)ifclassoffisscriptthenfelsescriptproperty|λ|:fendscriptendifendmReturn-- product :: [Num] -> Numonproduct(xs)scriptmultiplyon|λ|(a,b)a*bend|λ|endscriptfoldl(multiply,1,xs)endproduct
Output:
39916800

Arendelle

< n >{ @n = 0 ,   ( return , 1 ),     ( return ,       @n * !factorial( @n - ! )   )}

ArkScript

Works with:ArkScript version 4.0.0
(let factorial (fun (n) {  (mut result 1)  (mut i 2)  (while (< i n) {    (set result (* result i))    (set i (+ 1 i)) })  result }))(import std.List)(list:forEach  (list:iota 0 8)  (fun (n) (print n "\t" (factorial n))))
Output:
011122364245120672075040

ARM Assembly

Works with:as version Raspberry Pi
/* ARM assembly Raspberry PI  *//*  program factorial.s   *//* Constantes    */.equ STDOUT, 1     @ Linux output console.equ EXIT,   1     @ Linux syscall.equ WRITE,  4     @ Linux syscall/*********************************//* Initialized data              *//*********************************/.dataszMessLargeNumber:   .asciz "Number N to large. \n"szMessNegNumber:      .asciz "Number N is negative. \n"szMessResult:  .ascii "Resultat = "      @ message resultsMessValeur:   .fill 12, 1, ' '                   .asciz "\n"/*********************************//* UnInitialized data            *//*********************************/.bss /*********************************//*  code section                 *//*********************************/.text.global main main:                @ entry of program     push {fp,lr}      @ saves 2 registers     mov r0,#-5    bl factorial    mov r0,#10    bl factorial    mov r0,#20    bl factorial100:   @ standard end of the program     mov r0, #0                  @ return code    pop {fp,lr}                 @restaur 2 registers    mov r7, #EXIT              @ request to exit program    swi 0                       @ perform the system call/********************************************//*     calculation                         *//********************************************//* r0 contains number N */factorial:    push {r1,r2,lr}    @ save  registres     cmp r0,#0    blt 99f    beq 100f    cmp r0,#1    beq 100f    bl calFactorial    cmp r0,#-1          @ overflow ?    beq 98f    ldr r1,iAdrsMessValeur                    bl conversion10       @ call function with 2 parameter (r0,r1)    ldr r0,iAdrszMessResult    bl affichageMess            @ display message    b 100f98:   @ display error message    ldr r0,iAdrszMessLargeNumber    bl affichageMess    b 100f99:  @ display error message    ldr r0,iAdrszMessNegNumber    bl affichageMess100:    pop {r1,r2,lr}    @ restaur registers     bx lr        @ return  iAdrszMessNegNumber:       .int szMessNegNumberiAdrszMessLargeNumber:    .int szMessLargeNumberiAdrsMessValeur:            .int sMessValeuriAdrszMessResult:          .int szMessResult/******************************************************************//*     calculation                         */ /******************************************************************//* r0 contains the number N */calFactorial:    cmp r0,#1          @ N = 1 ?    bxeq lr           @ yes -> return     push {fp,lr}    @ save  registers     sub sp,#4           @ 4 byte on the stack     mov fp,sp           @ fp <- start address stack    str r0,[fp]                    @ fp contains  N    sub r0,#1          @ call function with N - 1    bl calFactorial    cmp r0,#-1         @ error overflow ?    beq 100f         @ yes -> return    ldr r1,[fp]       @ load N    umull r0,r2,r1,r0   @ multiply result by N     cmp r2,#0           @ r2 is the hi rd  if <> 0 overflow    movne r0,#-1      @ if overflow  -1 -> r0100:    add sp,#4            @ free 4 bytes on stack    pop {fp,lr}    @ restau2 registers     bx lr        @ return  /******************************************************************//*     display text with size calculation                         */ /******************************************************************//* r0 contains the address of the message */affichageMess:    push {fp,lr}    /* save  registres */     push {r0,r1,r2,r7}    /* save others registers */    mov r2,#0   /* counter length */1:      /* loop length calculation */    ldrb r1,[r0,r2]  /* read octet start position + index */    cmp r1,#0       /* if 0 its over */    addne r2,r2,#1   /* else add 1 in the length */    bne 1b          /* and loop */                                /* so here r2 contains the length of the message */    mov r1,r0        /* address message in r1 */    mov r0,#STDOUT      /* code to write to the standard output Linux */    mov r7, #WRITE             /* code call system "write" */    swi #0                      /* call systeme */    pop {r0,r1,r2,r7}     /* restaur others registers */    pop {fp,lr}    /* restaur des  2 registres */     bx lr        /* return  *//******************************************************************//*     Converting a register to a decimal                                 */ /******************************************************************//* r0 contains value and r1 address area   */conversion10:    push {r1-r4,lr}    /* save registers */     mov r3,r1    mov r2,#101:   @ start loop    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1    add r1,#48        @ digit    strb r1,[r3,r2]  @ store digit on area    sub r2,#1         @ previous position    cmp r0,#0         @ stop if quotient = 0 */    bne 1b          @ else loop    @ and move spaves in first on area    mov r1,#' '   @ space2:    strb r1,[r3,r2]  @ store space in area    subs r2,#1       @ @ previous position    bge 2b           @ loop if r2 >= zéro 100:    pop {r1-r4,lr}    @ restaur registres     bx lr          @return/***************************************************//*   division par 10   signé                       *//* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*  /* and   http://www.hackersdelight.org/            *//***************************************************//* r0 dividende   *//* r0 quotient *//* r1 remainder  */divisionpar10:  /* r0 contains the argument to be divided by 10 */   push {r2-r4}   /* save registers  */   mov r4,r0    ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */   add r0, r2, r1         /* r0 <- r2 + r1 */   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */   pop {r2-r4}   bx lr                  /* leave function */   .align 4.Ls_magic_number_10: .word 0x66666667

ArnoldC

LISTEN TO ME VERY CAREFULLY factorialI NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE nGIVE THESE PEOPLE AIRBECAUSE I'M GOING TO SAY PLEASE nBULLS***I'LL BE BACK 1YOU HAVE NO RESPECT FOR LOGICHEY CHRISTMAS TREE productYOU SET US UP @NO PROBLEMOSTICK AROUND nGET TO THE CHOPPER productHERE IS MY INVITATION productYOU'RE FIRED nENOUGH TALKGET TO THE CHOPPER nHERE IS MY INVITATION nGET DOWN @NO PROBLEMOENOUGH TALKCHILLI'LL BE BACK productHASTA LA VISTA, BABY

Arturo

Recursive

factorial:function[n][switchn>0->n*factorialn-1->1]loop1..19[x]->print["Factorial of"x"="factorialx]

Fold

factorial:$[n][fold.seed:11..n[a,b][a*b]]loop1..19[x][print["Factorial of"x"="factorialx]]

Product

factorial:$[n][product1..n]loop1..19[x][print["Factorial of"x"="factorialx]]
Output:
Factorial of 1 = 1 Factorial of 2 = 2 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 Factorial of 6 = 720 Factorial of 7 = 5040 Factorial of 8 = 40320 Factorial of 9 = 362880 Factorial of 10 = 3628800 Factorial of 11 = 39916800 Factorial of 12 = 479001600 Factorial of 13 = 6227020800 Factorial of 14 = 87178291200 Factorial of 15 = 1307674368000 Factorial of 16 = 20922789888000 Factorial of 17 = 355687428096000 Factorial of 18 = 6402373705728000 Factorial of 19 = 121645100408832000

AsciiDots

/---------*--~-$#-&| /--;---\| [!]-\| *------++--*#1/| | /1#\ ||[*]*{-}-*~<+*?#-.*-------+-</\-#0----/

ATS

Iterative

funfact(  n: int) : int = res where{  var n: int = n  var res: int = 1  val () = while (n > 0) (res := res * n; n := n - 1)}

Recursive

funfactorial  (n:int): int =  if n > 0 then n * factorial(n-1) else 1// end of [factorial]

Tail-recursive

funfactorial  (n:int): int = let  fun loop(n: int, res: int): int =    if n > 0 then loop(n-1, n*res) else resin  loop(n, 1)end // end of [factorial]

Asymptote

Iterative

realfactorial(intn){realf=1;for(inti=2;i<=n;++i)f=f*i;returnf;}write("The factorials for the first 5 positive integers are:");for(intj=1;j<=5;++j)write(string(j)+"! = "+string(factorial(j)));

AutoHotkey

Iterative

MsgBox%factorial(4)factorial(n){result:=1Loop,%nresult*=A_IndexReturnresult}

Recursive

MsgBox%factorial(4)factorial(n){returnn>1?n--*factorial(n):1}

AutoIt

Iterative

;AutoIt Version: 3.2.10.0MsgBox(0,"Factorial",factorial(6))Funcfactorial($int)If$int<0ThenReturn0EndIf$fact=1For$i=1To$int$fact=$fact*$iNextReturn$factEndFunc

Recursive

;AutoIt Version: 3.2.10.0MsgBox(0,"Factorial",factorial(6))Funcfactorial($int)if$int<0Thenreturn0Elseif$int==0Thenreturn1EndIfreturn$int*factorial($int-1)EndFunc

Avail

Avail has a built-in factorial method using the standard exclamation point.

Assert: 7! = 5040;

Its implementation is quite simple, using iterativeleft fold_through_.

Method "_`!" is [n : [0..1] | 1];Method "_`!" is[n : [2..∞)|left fold 2 to n through [k : [2..∞), s : [2..∞) | k × s]];

AWK

Recursive

functionfact_r(n){if(n<=1)return1;returnn*fact_r(n-1);}

Iterative

functionfact(n){if(n<1)return1;r=1for(m=2;m<=n;m++){r*=m;}returnr}

Axe

Iterative

Lbl FACT1→RFor(I,1,r₁) R*I→REndRReturn

Recursive

Lbl FACTr₁??1,r₁*FACT(r₁-1)Return

Babel

Iterative

((main     {(0 1 2 3 4 5 6 7 8 9 10)    {fact ! %d nl <<}        each})(fact       {({dup 0 =}{ zap 1 }         {dup 1 =}{ zap 1 }         {1      }{ <- 1 {iter 1 + *} -> 1 - times })        cond}))

Recursive

((main     {(0 1 2 3 4 5 6 7 8 9 10)     {fact ! %d nl <<}    each})(fact       {({dup 0 =}{ zap 1 }         {dup 1 =}{ zap 1 }         {1      }{ dup 1 - fact ! *})        cond}))

When run, either code snippet generates the following

Output:
1126241207205040403203628803628800

bash

Recursive

factorial(){if[$1-le1]thenecho1elseresult=$(factorial$[$1-1])echo$((result*$1))fi}

Imperative

factorial(){declare-nI_result=$1declare-in=$2_result=1while((n>0));dolet_result*=nletn-=1done}

(the imperative version will write to a variable, and can be used asfactorial f 10; echo $f)

BASIC

Iterative

Works with:FreeBASIC
Works with:QBasic
Works with:RapidQ
FUNCTIONfactorial(nASInteger)ASIntegerDIMfASInteger,iASIntegerf=1FORi=2TOnf=f*iNEXTifactorial=fENDFUNCTION

Recursive

Works with:FreeBASIC
Works with:QBasic
Works with:RapidQ
FUNCTIONfactorial(nASInteger)ASIntegerIFn<2THENfactorial=1ELSEfactorial=n*factorial(n-1)ENDIFENDFUNCTION

Applesoft BASIC

Iterative

100 N = 4 : GOSUB 200"FACTORIAL110 PRINT N120 END200 N = INT(N)210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I220 RETURN

Recursive

 10 A = 768:L = 7 20  DATA 165,157,240,3 30  DATA 32,149,217,96 40  FOR I = A TO A + L 50  READ B: POKE I,B: NEXT  60 H = 256: POKE 12,A / H 70  POKE 11,A -  PEEK (12) * H 80  DEF  FN FA(N) =  USR (N < 2) + N *  FN FA(N - 1) 90  PRINT  FN FA(4)

http://hoop-la.ca/apple2/2013/usr-if-recursive-fn/

BaCon

Overflow occurs at 21 or greater. Negative values treated as 0.

' FactorialFUNCTIONfactorial(NUMBERn)TYPENUMBERIFn<=1THENRETURN1ELSERETURNn*factorial(n-1)ENDIFENDFUNCTIONn=VAL(TOKEN$(ARGUMENT$,2))PRINTn,factorial(n)FORMAT"%ld! = %ld\n"
Output:
prompt$ ./factorial 00! = 1prompt$ ./factorial 2020! = 2432902008176640000

BASIC256

Iterative

print"enter a number, n = ";inputnprintstring(n)+"! = "+string(factorial(n))functionfactorial(n)factorial=1ifn>0thenforp=1tonfactorial*=pnextpendifendfunction

Recursive

print "enter a number, n = ";input nprint string(n) + "! = " + string(factorial(n))function factorial(n)   if n > 0 then      factorial = n * factorial(n-1)   else      factorial = 1   end ifend function

BBC BASIC

Works with:BBC BASIC for Windows

18! is the largest that doesn't overflow.

*FLOAT64@%=&1010PRINTFNfactorial(18)ENDDEFFNfactorial(n)IFn<=1THEN=1ELSE=n*FNfactorial(n-1)
Output:
6402373705728000

CBASIC

Since CBASIC does not support recursion, only an iterative solution is possible

rem-returnn!deffn.factorial(n)f=1fori=1tonf=f*inextifn.factorial=freturnfendprint"Factorial Calculator"printprint" n          n!"print"-------------------"fork=1to14printusing"##  ###,###,###,###";k;fn.factorial(k)nextkend
Output:
Factorial Calculator n            n!------------------- 1                1 2                2 3                6 4               24 5              120 6              720 7            5,040 8           40,320 9          362,88010        3,628,80011       39,916,80012      479,001,60013    6,227,020,80014   87,178,291,200


Chipmunk Basic

Works with:Chipmunk Basic version 3.6.4

Iterative

100cls110limite=13120fori=0tolimite130printright$(str$(i),2);"! = ";tab(6);factoriali(i)140nexti150subfactoriali(n):'Iterative160f=1170ifn>1then180forj=2ton190f=f*j200nextj210endif220factoriali=f230endsub

Recursive

100cls110limite=13120fori=0tolimite130printright$(str$(i),2);"! = ";tab(6);factorialr(i)140nexti150subfactorialr(n):'Recursive160ifn<2then170f=1180else190f=n*factorialr(n-1)200endif210factorialr=f220endsub

Commodore BASIC

All numbers in Commodore BASIC are stored as floating-point with a 32-bit mantissa. The maximum representable value is 1.70141183 × 1038, so it can handle factorials up to 33! = 8.68331762 × 1036, but only keeps 32 bits of precision. That means that what you see is what you get; the mantissa for 33! is 8.68331762 exactly instead of 8.68331761881188649551819440128.

Iterative

10REM FACTORIAL20REM COMMODORE BASIC 2.030INPUT"N=";N:GOSUB10040PRINTN;"! =";F50GOTO30100REM FACTORIAL CALC USING SIMPLE LOOP110F=1120FORI=1TON130F=F*I140NEXT150RETURN

Recursive with memoization and demo

The demo stops at 13!, which is when the numbers start being formatted in scientific notation.

100 REM FACTORIAL110 DIM F(35): F(0)=1:  REM MEMOS120 DIM S(35): SP=0:    REM STACK+PTR130 FOR I=1 TO 13140 : S(SP)=I: SP=SP+1: REM PUSH(I)150 : GOSUB 200160 : SP=SP-1:          REM POP170 : PRINT I;"! = ";S(SP)180 NEXT I190 END200 REM FACTORIAL: S(SP-1) = S(SP-1)!210 IF F(S(SP-1)) THEN 240: REM MEMOIZED220 S(SP)=S(SP-1)-1: SP=SP+1: GOSUB 200: REM RECURSE230 SP=SP-1: F(S(SP-1))=S(SP-1)*S(SP): REM MEMOIZE240 S(SP-1)=F(S(SP-1)): REM PUSH(RESULT)250 RETURN
Output:
 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 ! =   6.2270208E+09

Craft Basic

'accurate between 1-12print"version 1 without function"fori=1to12letn=iletf=1doletf=f*nletn=n-1loopn>0printf," ",waitnextiprintnewline,newline,"version 2 with function"fori=1to12printfactorial(i)," ",nexti
Output:
version 1 without function

1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600

version 2 with function

1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600

FreeBASIC

' FB 1.05.0 Win64FunctionFactorial_Iterative(nAsInteger)AsIntegerVarresult=1ForiAsInteger=2Tonresult*=iNextReturnresultEndFunctionFunctionFactorial_Recursive(nAsInteger)AsIntegerIfn=0ThenReturn1Returnn*Factorial_Recursive(n-1)EndFunctionForiAsInteger=1To5Printi;" =>";Factorial_Iterative(i)NextForiAsInteger=6To10PrintUsing"##";i;Print" =>";Factorial_Recursive(i)NextPrintPrint"Press any key to quit"Sleep
Output:
 1 => 1 2 => 2 3 => 6 4 => 24 5 => 120 6 => 720 7 => 5040 8 => 40320 9 => 36288010 => 3628800

FTCBASIC

definef=1,n=0print"Factorial"print"Enter an integer: "\inputndoletf=f*n-1nloopn>0printfpauseend


Gambas

' Task: Factorial' Language: Gambas' Author: Sinuhe Masan (2019)' Function factorial iterativeFunctionfactorial_iter(numAsInteger)AsLongDimfactAsLongDimiAsIntegerfact=1Ifnum>1ThenFori=2Tonumfact=fact*iNextEndifReturnfactEnd' Function factorial recursiveFunctionfactorial_rec(numAsInteger)AsLongIfnum<=1ThenReturn1ElseReturnnum*factorial_rec(num-1)EndifEndPublicSubMain()Printfactorial_iter(6)Printfactorial_rec(7)End

Output:

7205040

GW-BASIC

10INPUT"Enter a non/negative integer: ",N20IFN<0THENGOTO1030F#=140IFN=0THENPRINTF#:END50F#=F#*N60N=N-170GOTO40

IS-BASIC

100 DEF FACT(N)110   LET F=1120   FOR I=2 TO N130     LET F=F*I140   NEXT150   LET FACT=F160 END DEF

Liberty BASIC

Works with:Just BASIC
    for i =0 to 40        print " FactorialI( "; using( "####", i); ") = "; factorialI( i)        print " FactorialR( "; using( "####", i); ") = "; factorialR( i)    next i    wait    function factorialI( n)        if n >1 then            f =1            For i = 2 To n                f = f * i            Next i        else            f =1        end if    factorialI =f    end function    function factorialR( n)        if n <2 then            f =1        else            f =n *factorialR( n -1)        end if    factorialR =f    end function    end

Microsoft Small Basic

'Factorial - smallbasic - 05/01/2019For n = 1 To 25    f = 1    For i = 1 To n        f = f * i    EndFor    TextWindow.WriteLine("Factorial(" + n + ")=" + f)EndFor
Output:
Factorial(25)=15511210043330985984000000

Minimal BASIC

Works with:QBasic version 1.1
Works with:Chipmunk Basic
Works with:GW-BASIC
Works with:MSX_Basic
10PRINT"ENTER AN INTEGER:";20INPUTN30LETF=140FORK=1TON50LETF=F*K60NEXTK70PRINTF80END

MSX Basic

Works with:QBasic version 1.1
Works with:Chipmunk Basic
Works with:GW-BASIC
Works with:PC-BASIC version any
100CLS110LIMITE=13120FORN=0TOLIMITE130PRINTRIGHT$(STR$(N),2);"! = ";135GOSUB150137PRINTI140NEXTN145END150'factorial iterative160I=1170IFN>1THENFORJ=2TON:I=I*J:NEXTJ230RETURN

Palo Alto Tiny BASIC

10REM FACTORIAL20INPUT"ENTER AN INTEGER"N30LETF=140FORK=1TON50LETF=F*K60NEXTK70PRINTF80STOP
Output:
ENTER AN INTEGER:7   5040

PowerBASIC

function fact1#(n%)local i%,r#r#=1for i%=1 to n%r#=r#*i%nextfact1#=r#end functionfunction fact2#(n%)if n%<=2 then fact2#=n% else fact2#=fact2#(n%-1)*n%end functionfor i%=1 to 20print i%,fact1#(i%),fact2#(i%)next

PureBasic

Iterative

Procedurefactorial(n)Protectedi,f=1Fori=2Tonf=f*iNextProcedureReturnfEndProcedure

Recursive

ProcedureFactorial(n)Ifn<2ProcedureReturn1ElseProcedureReturnn*Factorial(n-1)EndIfEndProcedure

QB64

REDIMfac#(0)Factorialfac#(),655,10,power#PRINTpower#SUBFactorial(fac#(),n&,numdigits%,power#)power#=0fac#(0)=1remain#=0stx&=0slog#=0NumDiv#=10^numdigits%FORfac#=1TOn&slog#=slog#+LOG(fac#)/LOG(10)FORx&=0TOstx&fac#(x&)=fac#(x&)*fac#+remain#tx#=fac#(x&)MODNumDiv#remain#=(fac#(x&)-tx#)/NumDiv#fac#(x&)=tx#NEXTIFremain#>0THENstx&=UBOUND(fac#)+1REDIM_PRESERVEfac#(stx&)fac#(stx&)=remain#remain#=0ENDIFNEXTscanz&=LBOUND(fac#)DOIFscanz&<UBOUND(fac#)THENIFfac#(scanz&)THENEXITDOELSEscanz&=scanz&+1ENDIFELSEEXITDOENDIFLOOPFORx&=UBOUND(fac#)TOscanz&STEP-1m$=LTRIM$(RTRIM$(STR$(fac#(x&))))IFx&<UBOUND(fac#)THENWHILELEN(m$)<numdigits%m$="0"+m$WENDENDIFPRINTm$;" ";power#=power#+LEN(m$)NEXTpower#=power#+(scanz&*numdigits%)-1PRINTslog#ENDSUB

QB64_2022

N=18:DIMFASDOUBLE' Factorial.bas from RussiaF=1:FORI=1TON:F=F*I:NEXT:PRINTF'N = 5 F = 120'N = 18 F = 6402373705728000

Quite BASIC

Works with:QBasic version 1.1
Works with:Chipmunk Basic
Works with:GW-BASIC
Works with:MSX_Basic
10CLS20INPUT"Enter an integer:";N30LETF=140FORK=1TON50LETF=F*K60NEXTK70PRINTF80END

Run BASIC

for i = 0 to 100   print " fctrI(";right$("00";str$(i),2); ") = "; fctrI(i)   print " fctrR(";right$("00";str$(i),2); ") = "; fctrR(i)next iend function fctrI(n)fctrI = 1 if n >1 then  for i = 2 To n    fctrI = fctrI * i  next i end ifend functionfunction fctrR(n)fctrR = 1if n > 1 then fctrR = n * fctrR(n -1)end function

Sinclair ZX81 BASIC

Iterative

10INPUTN20LETFACT=130FORI=2TON40LETFACT=FACT*I50NEXTI60PRINTFACT
Input:
13
Output:
6227020800

Recursive

AGOSUB is just a procedure call that doesn't pass parameters.

10INPUTN20LETFACT=130GOSUB6040PRINTFACT50STOP60IFN=0THENRETURN70LETFACT=FACT*N80LETN=N-190GOSUB60100RETURN
Input:
13
Output:
6227020800

SmallBASIC

n=10factorial=1forii=2tonfactorial=factorial*iinextprintfactorial

TI-83 BASIC

TI-83 BASIC has a built-in factorial operator: x! is the factorial of x. An other way is to use a combination of prod() and seq() functions:

10→NN! ---> 362880prod(seq(I,I,1,N)) ---> 362880

Note: maximum integer value is:

13!                     ---> 6227020800

TI-89 BASIC

TI-89 BASIC also has the factorial function built in: x! is the factorial of x.

factorial(x)Func  Return Π(y,y,1,x)EndFunc

Π is the standard product operator:Π(expr,i,a,b)TI89=i=abexprMath notation{\displaystyle {\displaystyle \overbrace {\Pi (\mathrm {expr} ,i,a,b)} ^{\mathrm {TI-89} }=\overbrace {\prod _{i=a}^{b}\mathrm {expr} } ^{\text{Math notation}}}}

Tiny BASIC

Works with:TinyBasic
10LETF=120PRINT"Enter an integer."30INPUTN40IFN=0THENGOTO8050LETF=F*N60LETN=N-170GOTO4080PRINTF90END

True BASIC

Iterative

Works with:QBasic
DEFFNfactorial(n)LETf=1FORi=2TOnLETf=f*iNEXTiLETFNfactorial=fENDDEFEND

Recursive

Works with:QBasic
DEFFNfactorial(n)IFn<2THENLETFNfactorial=1ELSELETFNfactorial=n*FNfactorial(n-1)ENDIFENDDEFEND

VBA

PublicFunctionfactorial(nAsInteger)AsLongfactorial=WorksheetFunction.Fact(n)EndFunction

==VBA ==

For numbers < 170 only

OptionExplicitSubMain()DimiAsIntegerFori=1To17Debug.Print"Factorial "&i&" , recursive : "&FactRec(i)&", iterative : "&FactIter(i)NextDebug.Print"Factorial 120, recursive : "&FactRec(120)&", iterative : "&FactIter(120)EndSubPrivateFunctionFactRec(NbAsInteger)AsStringIfNb>170OrNb<0ThenFactRec=0:ExitFunctionIfNb=1OrNb=0ThenFactRec=1ElseFactRec=Nb*FactRec(Nb-1)EndIfEndFunctionPrivateFunctionFactIter(NbAsInteger)IfNb>170OrNb<0ThenFactIter=0:ExitFunctionDimiAsInteger,FF=1Fori=1ToNbF=F*iNextiFactIter=FEndFunction
Output:
Factorial 1 , recursive : 1, iterative : 1Factorial 2 , recursive : 2, iterative : 2Factorial 3 , recursive : 6, iterative : 6Factorial 4 , recursive : 24, iterative : 24Factorial 5 , recursive : 120, iterative : 120Factorial 6 , recursive : 720, iterative : 720Factorial 7 , recursive : 5040, iterative : 5040Factorial 8 , recursive : 40320, iterative : 40320Factorial 9 , recursive : 362880, iterative : 362880Factorial 10 , recursive : 3628800, iterative : 3628800Factorial 11 , recursive : 39916800, iterative : 39916800Factorial 12 , recursive : 479001600, iterative : 479001600Factorial 13 , recursive : 6227020800, iterative : 6227020800Factorial 14 , recursive : 87178291200, iterative : 87178291200Factorial 15 , recursive : 1307674368000, iterative : 1307674368000Factorial 16 , recursive : 20922789888000, iterative : 20922789888000Factorial 17 , recursive : 355687428096000, iterative : 355687428096000Factorial 120, recursive : 6,68950291344919E+198, iterative : 6,68950291344912E+198

VBScript

Optimized with memoization, works for numbers up to 170 (because of the limitations on Doubles), exits if -1 is input

DimlookupTable(170),returnTable(170),currentPosition,inputcurrentPosition=0DoWhileTrueinput=InputBox("Please type a number (-1 to quit):")MsgBox"The factorial of "&input&" is "&factorial(CDbl(input))LoopFunctionfactorial(x)Ifx=-1ThenWScript.Quit0EndIfDimtemptemp=lookup(x)Ifx<=1Thenfactorial=1ElseIftemp<>0Thenfactorial=tempElsetemp=factorial(x-1)*xstorex,tempfactorial=tempEndIfEndFunctionFunctionlookup(x)DimiFori=0TocurrentPosition-1IflookupTable(i)=xThenlookup=returnTable(i)ExitFunctionEndIfNextlookup=0EndFunctionFunctionstore(x,y)lookupTable(currentPosition)=xreturnTable(currentPosition)=ycurrentPosition=currentPosition+1EndFunction

Visual Basic

Works with:Visual Basic version VB6 Standard
OptionExplicitSubMain()DimiAsVariantFori=1To27Debug.Print"Factorial("&i&")= , recursive : "&Format$(FactRec(i),"#,###")&" - iterative : "&Format$(FactIter(i),"#,####")NextEndSub'MainPrivateFunctionFactRec(nAsVariant)AsVariantn=CDec(n)Ifn=1ThenFactRec=1#ElseFactRec=n*FactRec(n-1)EndIfEndFunction'FactRecPrivateFunctionFactIter(nAsVariant)DimiAsVariant,fAsVariantf=1#Fori=1#ToCDec(n)f=f*iNextiFactIter=fEndFunction'FactIter
Output:
Factorial(1)= , recursive : 1 - iterative : 1Factorial(2)= , recursive : 2 - iterative : 2Factorial(3)= , recursive : 6 - iterative : 6Factorial(4)= , recursive : 24 - iterative : 24Factorial(5)= , recursive : 120 - iterative : 120Factorial(6)= , recursive : 720 - iterative : 720Factorial(7)= , recursive : 5,040 - iterative : 5,040Factorial(8)= , recursive : 40,320 - iterative : 40,320Factorial(9)= , recursive : 362,880 - iterative : 362,880Factorial(10)= , recursive : 3,628,800 - iterative : 3,628,800Factorial(11)= , recursive : 39,916,800 - iterative : 39,916,800Factorial(12)= , recursive : 479,001,600 - iterative : 479,001,600Factorial(13)= , recursive : 6,227,020,800 - iterative : 6,227,020,800Factorial(14)= , recursive : 87,178,291,200 - iterative : 87,178,291,200Factorial(15)= , recursive : 1,307,674,368,000 - iterative : 1,307,674,368,000Factorial(16)= , recursive : 20,922,789,888,000 - iterative : 20,922,789,888,000Factorial(17)= , recursive : 355,687,428,096,000 - iterative : 355,687,428,096,000Factorial(18)= , recursive : 6,402,373,705,728,000 - iterative : 6,402,373,705,728,000Factorial(19)= , recursive : 121,645,100,408,832,000 - iterative : 121,645,100,408,832,000Factorial(20)= , recursive : 2,432,902,008,176,640,000 - iterative : 2,432,902,008,176,640,000Factorial(21)= , recursive : 51,090,942,171,709,440,000 - iterative : 51,090,942,171,709,440,000Factorial(22)= , recursive : 1,124,000,727,777,607,680,000 - iterative : 1,124,000,727,777,607,680,000Factorial(23)= , recursive : 25,852,016,738,884,976,640,000 - iterative : 25,852,016,738,884,976,640,000Factorial(24)= , recursive : 620,448,401,733,239,439,360,000 - iterative : 620,448,401,733,239,439,360,000Factorial(25)= , recursive : 15,511,210,043,330,985,984,000,000 - iterative : 15,511,210,043,330,985,984,000,000Factorial(26)= , recursive : 403,291,461,126,605,635,584,000,000 - iterative : 403,291,461,126,605,635,584,000,000Factorial(27)= , recursive : 10,888,869,450,418,352,160,768,000,000 - iterative : 10,888,869,450,418,352,160,768,000,000

Visual Basic .NET

Translation of:C#
Library:System.Numerics

Various type implementations follow. No error checking, so don't try to evaluate a number less than zero, or too large of a number.

ImportsSystemImportsSystem.NumericsImportsSystem.LinqModuleModule1' Type Double:FunctionDofactorialI(nAsInteger)AsDouble' IterativeDofactorialI=1:ForiAsInteger=1Ton:DofactorialI*=i:NextEndFunction' Type Unsigned Long:FunctionULfactorialI(nAsInteger)AsULong' IterativeULfactorialI=1:ForiAsInteger=1Ton:ULfactorialI*=i:NextEndFunction' Type Decimal:FunctionDefactorialI(nAsInteger)AsDecimal' IterativeDefactorialI=1:ForiAsInteger=1Ton:DefactorialI*=i:NextEndFunction' Extends precision by "dehydrating" and "rehydrating" the powers of tenFunctionDxfactorialI(nAsInteger)AsString' IterativeDimfactorialasDecimal=1,zerosasinteger=0ForiAsInteger=1Ton:factorial*=iIffactorialMod10=0Thenfactorial/=10:zeros+=1Next:Returnfactorial.ToString()&NewString("0",zeros)EndFunction' Arbitrary Precision:FunctionFactorialI(nAsInteger)AsBigInteger' IterativefactorialI=1:ForiAsInteger=1Ton:factorialI*=i:NextEndFunctionFunctionFactorial(numberAsInteger)AsBigInteger' FunctionalReturnEnumerable.Range(1,number).Aggregate(NewBigInteger(1),Function(acc,num)acc*num)EndFunctionSubMain()Console.WriteLine("Double  : {0}! = {1:0}",20,DoFactorialI(20))Console.WriteLine("ULong   : {0}! = {1:0}",20,ULFactorialI(20))Console.WriteLine("Decimal : {0}! = {1:0}",27,DeFactorialI(27))Console.WriteLine("Dec.Ext : {0}! = {1:0}",32,DxFactorialI(32))Console.WriteLine("Arb.Prec: {0}! = {1}",250,Factorial(250))EndSubEndModule
Output:

Note that the first four are the maximum possible for their type without causing a run-time error.

Double  : 20! = 2432902008176640000ULong   : 20! = 2432902008176640000Decimal : 27! = 10888869450418352160768000000Dec.Ext : 32! = 263130836933693530167218012160000000Arb.Prec: 250! = 3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000

Yabasic

// recursivesub factorial(n)    if n > 1 then return n * factorial(n - 1) else return 1 end ifend sub//iterativesub factorial2(n)    local i, t        t = 1    for i = 1 to n        t = t * i    next    return tend subfor n = 0 to 9    print "Factorial(", n, ") = ", factorial(n)next

ZX Spectrum Basic

Iterative

10LETx=5:GOSUB1000:PRINT"5! = ";r999STOP1000REM *************1001REM * FACTORIAL *1002REM *************1010LETr=11020IFx<2THENRETURN1030FORi=2TOx:LETr=r*i:NEXTi1040RETURN
Output:
5! = 120

Recursive

Using VAL for delayed evaluation and AND's ability to return given string or empty, we can now control the program flow within an expression in a manner akin to LISP's cond:

DEF FNf(n)=VAL(("1"ANDn<=0)+("n*FN f(n-1)"ANDn>0))

But, truth be told, the parameter n does not withstand recursive calling. Changing the order of the product gives naught:

DEF FNf(n)=VAL(("1"ANDn<=0)+("FN f(n-1)*n"ANDn>0))

Some little tricks with string slicing can get us there though:

DEF FNf(n)=VAL"n*FN f(n-1)*1"((n<1)*10+1TO)

(lack of spaces important) will jump to the 11th character of the string ("1") on the last iteration, allowing the function call to unroll.

Batch File

@echo offset/px=set/afs=%x%-1sety=%x%FOR/L%%aIN(%fs%,-1,1)DOSET/ay*=%%aif%x%EQU 0sety=1echo%y%pauseexit

bc

#!/usr/bin/bc-qdefine f(x){if(x<=1)return(1);return(f(x-1)* x)}f(1000)quit

Beads

beads 1 program Factorial//  only works for cardinal numbers 0..Ncalc main_initlog to_str(Iterative(4))  //  24log to_str(Recursive(5))  //  120calc Iterative(n:num--  number of iterations):num   --  resultvar total = 1loop from:2 to:n index:ixtotal = ix * total return totalcalc Recursive dittoif n <= 1return 1elsereturn n * Recursive(n-1)
Output:
24120

beeswax

Infinite loop for enteringn and getting the resultn!:

        p      <_>1FT"pF>M"p~.~d      >Pd  >~{Np d             <

Calculaten! only once:

       p      <_1FT"pF>M"p~.~d     >Pd  >~{;

Limits for UInt64 numbers apply to both examples.

Examples:i indicates that the program expects the user to enter an integer.

julia>beeswax("factorial.bswx")i01i11i22i36i103628800i2217196083355034583040

Input of negative numbers forces the program to quit with an error message.

Befunge

&1\>:vv*<^-1:_$>\:|@.$<

Binary Lambda Calculus

Factorial on Church numerals in the lambda calculus isλn.λf.n(λf.λn.n(f(λf.λx.n f(f x))))(λx.f)(λx.x) (seehttps://github.com/tromp/AIT/blob/master/numerals/fac.lam) which in BLC is the 57 bits

000001010111000000110011100000010111101100111010001100010

BQN

Fac×´1+↕!720Fac6

Bracmat

Compute 10! and checking that it is 3628800, the esoteric way

      (       =           .   !arg:0&1          |   !arg            *   ( (                   =   r                    .   !arg:?r                      &                           ' (                           .   !arg:0&1                            | !arg*(($r)$($r))$(!arg+-1)                          )                  )                $ (                   =   r                    .   !arg:?r                      &                           ' (                           .   !arg:0&1                            | !arg*(($r)$($r))$(!arg+-1)                          )                  )                )              $ (!arg+-1)      )    $ 10  : 3628800

This recursive lambda function is made in the following way (seehttp://en.wikipedia.org/wiki/Lambda_calculus):

Recursive lambda function for computing factorial.

   g := λr. λn.(1, if n = 0; else n × (r r (n-1)))   f := g g

or, translated to Bracmat, and computing 10!

      ( (=(r.!arg:?r&'(.!arg:0&1|!arg*(($r)$($r))$(!arg+-1)))):?g    & (!g$!g):?f    & !f$10    )

The following is a straightforward recursive solution. Stack overflow occurs at some point, above 4243! in my case (Win XP).

  factorial=.!arg:~>1|!arg*factorial$(!arg+-1)
  factorial$4243  (13552 digits, 2.62 seconds) 52254301882898638594700346296120213182765268536522926.....0000000

Lastly, here is an iterative solution

(factorial=  r.   !arg:?r  &   whl    ' (!arg:>1&(!arg+-1:?arg)*!r:?r)  & !r);
   factorial$5000   (16326 digits) 422857792660554352220106420023358440539078667462664674884978240218135805270810820069089904787170638753708474665730068544587848606668381273 ... 000000

Brainf***

Prints sequential factorials in an infinite loop.

>++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>]

Brat

factorial = { x |  true? x == 0 1 { x * factorial(x - 1)}}

Bruijn

Implementation for numbers encoded in balanced ternary using Mixfix syntax defined in the Math module:

:import std/Math .factorial [∏ (+1) → 0 | [0]]:test ((factorial (+10)) =? (+3628800)) ([[1]])

Burlesque

Using the builtinFactorial function:

blsq ) 6?!720

Burlesque does not have functions nor is it iterative. Burlesque's strength are its implicit loops.

Following examples display other ways to calculate the factorial function:

blsq ) 1 6r@pd720blsq ) 1 6r@{?*}r[720blsq ) 2 6r@(.*)\/[[1+]e!.*720blsq ) 1 6r@p^{.*}5E!720blsq ) 6ropd720blsq ) 7ro)(.*){0 1 11}die!720

C

Iterative

intfactorial(intn){intresult=1;for(inti=1;i<=n;++i)result*=i;returnresult;}

Handle negative n (returning -1)

intfactorialSafe(intn){intresult=1;if(n<0)return-1;for(inti=1;i<=n;++i)result*=i;returnresult;}

Recursive

intfactorial(intn){returnn==0?1:n*factorial(n-1);}

Handle negative n (returning -1).

intfactorialSafe(intn){returnn<0?-1:n==0?1:n*factorialSafe(n-1);}

Tail Recursive

Safe with some compilers (for example: GCC with -O2, LLVM's clang)

intfac_aux(intn,intacc){returnn<1?acc:fac_aux(n-1,acc*n);}intfac_auxSafe(intn,intacc){returnn<0?-1:n<1?acc:fac_aux(n-1,acc*n);}intfactorial(intn){returnfac_aux(n,1);}

Obfuscated

This is simply beautiful,1995 IOCCC winning entry by Michael Savastio, largest factorial possible : 429539!

#include<stdio.h>#define l11l 0xFFFF#define ll1 for#define ll111 if#define l1l1 unsigned#define l111 struct#define lll11 short#define ll11l long#define ll1ll putchar#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1;#define l1ll1 *lllll++=l1ll%10000;l1ll/=10000;#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\lllll=(l1=l1->lll1l)->lll;ll=1-1;#define llll 1000l111llll1{l111llll1*lll1l,*ll1l1;l1l1lll11lll[llll];};main(){l111llll1*ll11,*l1l,*l1,*ll1l,*malloc();l1l1ll11ll1ll;ll11ll11,ll,l;l1l1lll11*lll1,*lllll;ll1(l=1-1;l<14;ll1ll("\t\"8)>l\"9!.)>vl"[l]^'L'),++l);scanf("%d",&l);l1l1l(l1l)l1l1l(ll11)(l1=l1l)->lll[l1l->lll[1-1]=1]=l11l;ll1(l11=1+1;l11<=l;++l11){l1=ll11;lll1=(ll1l=(ll11=l1l))->lll;lllll=(l1l=l1)->lll;ll=(l1ll=1-1);ll1(;ll1l->lll1l||l11l!=*lll1;){l1ll+=l11**lll1++;l1ll1ll111(++ll>llll){l1llllll1=(ll1l=ll1l->lll1l)->lll;}}ll1(;l1ll;){l1ll1ll111(++ll>=llll){l1lll}}*lllll=l11l;}ll1(l=(ll=1-1);(l<llll)&&(l1->lll[l]!=l11l);++l);ll1(;l1;l1=l1->ll1l1,l=llll){ll1(--l;l>=1-1;--l,++ll)printf((ll)?((ll%19)?"%04d":(ll=19,"\n%04d")):"%4d",l1->lll[l]);}ll1ll(10);}

C#

Iterative

usingSystem;classProgram{staticintFactorial(intnumber){if(number<0)thrownewArgumentOutOfRangeException(nameof(number),number,"Must be zero or a positive number.");varaccumulator=1;for(varfactor=1;factor<=number;factor++){accumulator*=factor;}returnaccumulator;}staticvoidMain(){Console.WriteLine(Factorial(10));}}

Recursive

usingSystem;classProgram{staticintFactorial(intnumber){if(number<0)thrownewArgumentOutOfRangeException(nameof(number),number,"Must be zero or a positive number.");returnnumber==0?1:number*Factorial(number-1);}staticvoidMain(){Console.WriteLine(Factorial(10));}}

Tail Recursive

usingSystem;classProgram{staticintFactorial(intnumber){if(number<0)thrownewArgumentOutOfRangeException(nameof(number),number,"Must be zero or a positive number.");returnFactorial(number,1);}staticintFactorial(intnumber,intaccumulator){if(number<0)thrownewArgumentOutOfRangeException(nameof(number),number,"Must be zero or a positive number.");if(accumulator<1)thrownewArgumentOutOfRangeException(nameof(accumulator),accumulator,"Must be a positive number.");returnnumber==0?accumulator:Factorial(number-1,number*accumulator);}staticvoidMain(){Console.WriteLine(Factorial(10));}}

Functional

usingSystem;usingSystem.Linq;classProgram{staticintFactorial(intnumber){returnEnumerable.Range(1,number).Aggregate((accumulator,factor)=>accumulator*factor);}staticvoidMain(){Console.WriteLine(Factorial(10));}}

Arbitrary Precision

Library:System.Numerics

Factorial() can calculate 200000! in around 40 seconds over at Tio.run.
FactorialQ() can calculate 1000000! in around 40 seconds over at Tio.run.

The "product tree" algorithm multiplies pairs of items on a list until there is only one item. Even though around the same number of multiply operations occurs (compared to the plain "accumulator" method), this is faster because the "bigger" numbers are generated near the end of the algorithm, instead of around halfway through. There is a significant space overhead incurred due to the creation of the temporary array to hold the partial results. The additional time overhead for array creation is negligible compared with the time savings of not dealing with the very large numbers until near the end of the algorithm.

For example, for 50!, here are the number of digits created for each product for either method:
plain:
1 1 1 2 3 3 4 5 6 7 8 9 10 11 13 14 15 16 18 19 20 22 23 24 26 27 29 30 31 33 34 36 37 39 41 42 44 45 47 48 50 52 53 55 57 58 60 62 63 65
product tree:
2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 5 5 5 6 6 6 6 6 6 6 6 6 8 11 11 11 11 11 13 21 21 23 42 65

One can see the plain method increases linearly up to the final value of 65. The product tree method stays low for quite awhile, then jumps up at the end.

For 200000!, when one sums up the number of digits of each product for all 199999 multiplications, the plain method is nearly 93 billion, while the product tree method is only about 17.3 million.

usingSystem;usingSystem.Numerics;usingSystem.Linq;classProgram{staticBigIntegerfactorial(intn)// iterative{BigIntegeracc=1;for(inti=1;i<=n;i++)acc*=i;returnacc;}staticpublicBigIntegerFactorial(intnumber)// functional{returnEnumerable.Range(1,number).Aggregate(newBigInteger(1),(acc,num)=>acc*num);}staticpublicBIFactorialQ(intnumber)// functional quick, uses prodtree method{vars=Enumerable.Range(1,number).Select(num=>newBI(num)).ToArray();inttop=s.Length,nt,i,j;while(top>1){for(i=0,j=top,nt=top>>1;i<nt;i++)s[i]*=s[--j];top=nt+((top&1)==1?1:0);}returns[0];}staticvoidMain(string[]args){Console.WriteLine(Factorial(250));}}
Output:
3232856260909107732320814552024368470994843717673780666747942427112823747555111209488817915371028199450928507353189432926730931712808990822791030279071281921676527240189264733218041186261006832925365133678939089569935713530175040513178760077247933065402339006164825552248819436572586057399222641254832982204849137721776650641276858807153128978777672951913990844377478702589172973255150283241787320658188482062478582659808848825548800000000000000000000000000000000000000000000000000000000000000

C++

The C versions work unchanged with C++, however, here is another possibility using the STL and boost:

#include<boost/iterator/counting_iterator.hpp>#include<algorithm>intfactorial(intn){// last is one-past-endreturnstd::accumulate(boost::counting_iterator<int>(1),boost::counting_iterator<int>(n+1),1,std::multiplies<int>());}

Iterative

This version of the program is iterative, with a while loop.

//iteration with whilelonglongintfactorial(longlongintn){longlongintr=1;while(1<n)r*=n--;returnr;}

Template

template<intN>structFactorial{enum{value=N*Factorial<N-1>::value};};template<>structFactorial<0>{enum{value=1};};// Factorial<4>::value == 24// Factorial<0>::value == 1voidfoo(){intx=Factorial<4>::value;// == 24inty=Factorial<0>::value;// == 1}

Compare all Solutions (except the meta)

#include<algorithm>#include<chrono>#include<iostream>#include<numeric>#include<vector>#include<boost/iterator/counting_iterator.hpp>usingulli=unsignedlonglongint;// bad style do-while and wrong for Factorial1(0LL) -> 0 !!!ulliFactorial1(ullim_nValue){ulliresult=m_nValue;ulliresult_next;ullipc=m_nValue;do{result_next=result*(pc-1);result=result_next;pc--;}while(pc>2);returnresult;}// iteration with whileulliFactorial2(ullin){ullir=1;while(1<n)r*=n--;returnr;}// recursiveulliFactorial3(ullin){returnn<2?1:n*Factorial3(n-1);}// tail recursiveinlineulli_fac_aux(ullin,ulliacc){returnn<1?acc:_fac_aux(n-1,acc*n);}ulliFactorial4(ullin){return_fac_aux(n,1);}// accumulate with functorulliFactorial5(ullin){// last is one-past-endreturnstd::accumulate(boost::counting_iterator<ulli>(1ULL),boost::counting_iterator<ulli>(n+1ULL),1ULL,std::multiplies<ulli>());}// accumulate with lambdaulliFactorial6(ullin){// last is one-past-endreturnstd::accumulate(boost::counting_iterator<ulli>(1ULL),boost::counting_iterator<ulli>(n+1ULL),1ULL,[](ullia,ullib){returna*b;});}intmain(){ulliv=20;// max value with unsigned long long intulliresult;std::cout<<std::fixed;usingduration=std::chrono::duration<double,std::micro>;{autot1=std::chrono::high_resolution_clock::now();result=Factorial1(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"do-while(1)               result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}{autot1=std::chrono::high_resolution_clock::now();result=Factorial2(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"while(2)                  result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}{autot1=std::chrono::high_resolution_clock::now();result=Factorial3(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"recursive(3)              result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}{autot1=std::chrono::high_resolution_clock::now();result=Factorial3(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"tail recursive(4)         result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}{autot1=std::chrono::high_resolution_clock::now();result=Factorial5(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"std::accumulate(5)        result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}{autot1=std::chrono::high_resolution_clock::now();result=Factorial6(v);autot2=std::chrono::high_resolution_clock::now();std::cout<<"std::accumulate lambda(6) result "<<result<<" took "<<duration(t2-t1).count()<<" µs\n";}}
do-while(1)               result 2432902008176640000 took 0.110000 µswhile(2)                  result 2432902008176640000 took 0.078000 µsrecursive(3)              result 2432902008176640000 took 0.057000 µstail recursive(4)         result 2432902008176640000 took 0.056000 µsstd::accumulate(5)        result 2432902008176640000 took 0.056000 µsstd::accumulate lambda(6) result 2432902008176640000 took 0.079000 µs

C3

Iterative

fn int factorial(int n){    int result = 1;    for (int i = 1; i <= n; ++i)    {        result *= i;    }    return result;}

Recursive

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

Recursive macro

In this case the value of x is compiled to a constant.

macro int factorial($n){    $if ($n == 0):        return 1;    $else:        return $n * @factorial($n - 1);    $endif;}fn void test(){    int x = @factorial(10);}

Calcscript

(fn fac (n)  (eq (any= n (Same)) 1   (eq (any= n 1) 1  (* n (fac (- n 1))))))(fn loop (n i)  (d (t (any= n i))     (p (fac i))     (loop n (+ i 1))))(p (fac (Same)))(loop 10 1)
Output:
112624120720504040320362880

Cat

Taken direct from the Cat manual:

define rec_fac      { dup 1 <= [pop 1] [dec rec_fac *] if }

Ceylon

sharedvoidrun(){Integer?recursiveFactorial(Integern)=>switch(n<=>0)case(smaller)nullcase(equal)1case(larger)if(existsf=recursiveFactorial(n-1))thenn*felsenull;Integer?iterativeFactorial(Integern)=>switch(n<=>0)case(smaller)nullcase(equal)1case(larger)(1:n).reduce(times);for(Integeriin0..10){print("the iterative factorial of     ``i`` is ``iterativeFactorial(i) else "negative"``       and the recursive factorial of ``i`` is ``recursiveFactorial(i) else "negative"``\n");}}

Chapel

procfac(n){varr=1;foriin1..ndor*=i;returnr;}

Chef

Caramel Factorials.Only reads one value.Ingredients.1 g Caramel2 g FactorialsMethod.Take Factorials from refrigerator.Put Caramel into 1st mixing bowl.Verb the Factorials.Combine Factorials into 1st mixing bowl.Verb Factorials until verbed.Pour contents of the 1st mixing bowl into the 1st baking dish.Serves 1.

ChucK

Recursive

0=>inttotal;funintfactorial(inti){if(i==0)return1;else{i*factorial(i-1)=>total;}returntotal;}// == another wayfunintfactorial(intx){if(x<=1)return1;elsereturnx*factorial(x-1);}// callfactorial(5)=>intanswer;// testif(answer==120)<<<"success">>>;

Iterative

1 => int total;fun int factorial(int i){    while(i > 0)     {        total * i => total;        1 -=> i;    }    return total;}

Clay

Obviously there’s more than one way to skin a cat. Here’s a selection — recursive, iterative, and “functional” solutions.

factorialRec(n){if(n==0)return1;returnn*factorialRec(n-1);}factorialIter(n){for(iinrange(1,n))n*=i;returnn;}factorialFold(n){returnreduce(multiply,1,range(1,n+1));}

We could also do it at compile time, because — hey — why not?

[n|n>0]factorialStatic(staticn)=n*factorialStatic(staticn-1);overloadfactorialStatic(static0)=1;

Because a literal 1 has type Int32, these functions receive and return numbers of that type. We must be a bit more careful if we wish to permit other numeric types (e.g. for larger integers).

[N|Integer?(N)]factorial(n:N){if(n==0)returnN(1);returnn*factorial(n-1);}

And testing:

main(){println(factorialRec(5));// 120println(factorialIter(5));// 120println(factorialFold(5));// 120println(factorialStatic(static5));// 120println(factorial(Int64(20)));// 2432902008176640000}

Clio

Recursive

fn factorial n:  if n <= 1: n  else:     n * (n - 1 -> factorial)10 -> factorial -> print

CLIPS

(deffunctionfactorial(?a)(if(or(not(integerp?a))(<?a0))then(printoutt"Factorial Error!"crlf)else(if(=?a0)then1else(*?a(factorial(-?a1))))))

Clojure

Folding

(defnfactorial[x](apply*'(range2(incx))))

Recursive

(defn factorial [x]  (if (< x 2)      1      (*' x (factorial (dec x)))))

Tail recursive

(defn factorial [x]  (loop [x x         acc 1]    (if (< x 2)        acc        (recur (dec x) (*' acc x)))))

Trampolining

(defn factorial  ([x] (trampoline factorial x 1))  ([x acc]   (if (< x 2)     acc     #(factorial (dec x) (*' acc x)))))

CLU

factorial = proc (n: int) returns (int) signals (negative)    if n<0 then signal negative    elseif n=0 then return(1)    else return(n * factorial(n-1))    endend factorialstart_up = proc ()    po: stream := stream$primary_output()        for i: int in int$from_to(0, 10) do        fac: int := factorial(i)        stream$putl(po, int$unparse(i) || "! = " || int$unparse(fac))    endend start_up
Output:
0! = 11! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 3628800

CMake

function(factorial var n)  set(product 1)  foreach(i RANGE 2 ${n})    math(EXPR product "${product} * ${i}")  endforeach(i)  set(${var} ${product} PARENT_SCOPE)endfunction(factorial)factorial(f 12)message("12! = ${f}")

COBOL

The following functions have no need to check if their parameters are negative because they are unsigned.

Intrinsic Function

COBOL includes an intrinsic function which returns the factorial of its argument.

MOVE FUNCTION FACTORIAL(num) TO result

Iterative

Works with:GnuCOBOL
       IDENTIFICATION DIVISION.       FUNCTION-ID. factorial_iterative.       DATA DIVISION.       LOCAL-STORAGE SECTION.       01  i      PIC 9(38).       LINKAGE SECTION.       01  n      PIC 9(38).       01  ret    PIC 9(38).       PROCEDURE DIVISION USING BY VALUE n RETURNING ret.           MOVE 1 TO ret            PERFORM VARYING i FROM 2 BY 1 UNTIL n < i               MULTIPLY i BY ret           END-PERFORM            GOBACK.       END FUNCTION factorial_iterative.

Recursive

Works with:Visual COBOL
Works with:GnuCOBOL
       IDENTIFICATION DIVISION.       FUNCTION-ID. factorial_recursive.       DATA DIVISION.       LOCAL-STORAGE SECTION.       01  prev-n PIC 9(38).       LINKAGE SECTION.       01  n      PIC 9(38).       01  ret    PIC 9(38).       PROCEDURE DIVISION USING BY VALUE n RETURNING ret.           IF n = 0               MOVE 1 TO ret           ELSE               SUBTRACT 1 FROM n GIVING prev-n               MULTIPLY n BY factorial_recursive(prev-n) GIVING ret           END-IF            GOBACK.       END FUNCTION factorial_recursive.

Test

Works with:GnuCOBOL
       IDENTIFICATION DIVISION.       PROGRAM-ID. factorial_test.       ENVIRONMENT DIVISION.       CONFIGURATION SECTION.       REPOSITORY.           FUNCTION factorial_iterative           FUNCTION factorial_recursive.       DATA DIVISION.       LOCAL-STORAGE SECTION.       01  i      PIC 9(38).       PROCEDURE DIVISION.           DISPLAY               "i = "               WITH NO ADVANCING           END-DISPLAY.           ACCEPT i END-ACCEPT.           DISPLAY SPACE END-DISPLAY.           DISPLAY               "factorial_iterative(i) = "               factorial_iterative(i)           END-DISPLAY.           DISPLAY               "factorial_recursive(i) = "               factorial_recursive(i)           END-DISPLAY.           GOBACK.       END PROGRAM factorial_test.
Output:
i = 14factorial_iterative(i) = 00000000000000000000000000087178291200factorial_recursive(i) = 00000000000000000000000000087178291200

CoffeeScript

Several solutions are possible in #"ltr">

fac = (n) ->  if n <= 1    1  else    n * fac n-1

Functional

Works with:JavaScript version 1.8

(SeeMDC)

fac = (n) ->  [1..n].reduce (x,y) -> x*y

Comal

Recursive:

  PROC Recursive(n) CLOSED    r:=1    IF n>1 THEN       r:=n*Recursive(n-1)    ENDIF    RETURN r  ENDPROC Recursive

Combinator Calculus

With Church encoded numerals

With standard combinatorsS,B,C,K,I:

Sabc = ac(bc)Babc = a (bc)Cabc = acbKab  = aIa   = a0 fx = x = SKfx = KIfx1 fx = fx = IfxSUCC mfx =  f(mfx) = Bf(mf)x = SBmfxADD nmfx = nf(mfx) = B(nf)(mf)x = n SUCC m f xSUB nmfx =                      = n PRED m f xMULT nmfx = n(mf)x = Bnmfx      = n (ADD m) 0 f xPOW bnfx = nbfx = CIbnfx        = n (MULT b) 1 f xPRED nfx = n(Xf)(Kx)I     WHERE  X fri = i(rf)HALF nfx = nX(K(Kx))If    WHERE  X rif = i(rfi);; iteration: (MULT n (MULT ... (MULT 2 (MULT 1 1)) ...)) f xFACT1 nfx = n G K 1 1 f x     WHERE  G rai = r (MULT i a) (SUCC i);; recursion: (MULT 1 (MULT 2 (MULT ... (MULT n 1) ...))) f xFACT2 nfx = n G (K 1) 1 f x   WHERE  G ra  = MULT a (r (SUCC a))                                     G raf = a (r (SUCC a) f)       ;; = C(C(CI(SSCB(SB)))(KI))I;; direct code creation: (1 (2 (... (n f) ...))) xFACT  nfx = n G (K f) 1 x     WHERE  G ra  = a (r (SUCC a));; calculation:FACT (SUCC (SUCC 1)) f x;; => G (G (G (Kf))) 1 x;; => 1 (G (G (Kf)) 2) x;; => 1 (2 (G (Kf) 3)) x;; => 1 (2 (3 (Kf 4))) x;; => 1 (2 (3   f   )) x;; =>    2    (3 f)    x;; => 3 f     (3 f     x  );; => f (f (f (f (f (f x)))))

Church lists are right folds over the list's elements,[a,b,c] g z = g a (g b (g c z)) ; MAP f l g z = l (B g f) z. Church numerals areunary encodings, folds over lists of unimportant, indiscernible values, like[(),(),()], where the list's length represents the number, and the successor functionf is the partial application of a folding function,g ().

There's natural correspondence of functions for the two types, Church numbers and Church lists of units, with similar implementations,

ADD     <--->   APPENDSUCC    <--->   CONS0       <--->   NIL ISZERO  <--->   ISEMPTYPRED    <--->   TAILMULT    <--->   CARTESIAN_PRODUCTMIN     <--->   ZIP (or MAP2)

With Scott encoding

UsingY combinator

0 z s = z1 z s = s 0SUCC u z s = s uPRED m = m 0 I;; PRED 0 = 0 0 I = 0;; PRED (SUCC u) = SUCC u 0 I = I u = ufromChurch n = n SUCC 0toChurch n s z = Y (^rn. n z (B s r)) nADD  i j = Y (^rj. j i (B SUCC r)) j        ; i+j  = (SUCC^j)(i)         = Y (Qi) j  WHERE              Qirj = j i (B SUCC r)MULT i j = Y (^rj. j 0 (B (ADD i) r)) j     ; i*j  = ((ADD i)^j)(0)         = Y (Qi) j  WHERE              Qirj = j 0 (B (ADD i) r)EXPT i j = Y (^rj. j 1 (B (MULT i) r)) j    ; i**j = ((MULT i)^j)(1)         = Y (Qi) j  WHERE              Qirj = j 1 (B (MULT i) r)----FACT i   = Y (^ri. i 1 (B (MULT i) r)) i    ; i! = (i--)*(i--)*...*1         = Y Q i  WHERE              Qri = i 1 (B (MULT i) r)----;; testing> toChurch (FACT (SUCC (SUCC 1)))     ; factorial of 3=> ^sz.s(s(s(s(s(s z)))))             ; 6

Comefrom0x10

This is iterative; recursion is not possible in Comefrom0x10.

n = 5 # calculates n!acc = 1factorial  comefrom  comefrom accumulate if n < 1accumulate  comefrom factorial  acc = acc * n  comefrom factorial if n is 0  n = n - 1acc # prints the result

Common Lisp

Recursive:

(defun factorial (n)  (if (zerop n) 1 (* n (factorial (1- n)))))

or

(defun factorial (n)  (if (< n 2) 1 (* n (factorial (1- n)))))

Tail Recursive:

(defun factorial (n &optional (m 1))  (if (zerop n) m (factorial (1- n) (* m n))))

Iterative:

(defun factorial (n)  "Calculates N!"  (loop for result = 1 then (* result i)     for i from 2 to n      finally (return result)))

Functional:

(defun factorial (n)    (reduce #'* (loop for i from 1 to n collect i)))

Alternate solution

Works with:Allegro CL version 10.1
;; Project : Factorial(defun factorial (n)          (cond ((= n 1) 1)          (t (* n (factorial (- n 1))))))(format t "~a" "factorial of 8: ")(factorial 8)

Output:

factorial of 8: 40320

Computer/zero Assembly

Both these programs findx{\displaystyle {\displaystyle x}}!. Values ofx{\displaystyle {\displaystyle x}} higher than 5 are not supported, because their factorials will not fit into an unsigned byte.

Iterative

        LDA  x        BRZ  done_i   ; 0! = 1        STA  iloop_i: LDA  fact        STA  n        LDA  i        SUB  one        BRZ  done_i        STA  jloop_j: LDA  fact        ADD  n        STA  fact        LDA  j        SUB  one        BRZ  done_j        STA  j        JMP  loop_jdone_j: LDA  i        SUB  one        STA  i        JMP  loop_idone_i: LDA  fact        STPone:         1fact:        1i:           0j:           0n:           0x:           5

Lookup

Since there is only a small range of possible values ofx{\displaystyle {\displaystyle x}}, storing the answers and looking up the one we want is much more efficient than actually calculating them. This lookup version uses 5 bytes of code and 7 bytes of data and finds 5! in 5 instructions, whereas the iterative solution uses 23 bytes of code and 6 bytes of data and takes 122 instructions to find 5!.

        LDA  load        ADD  x        STA  loadload:   LDA  fact        STPfact:        1             1             2             6             24             120x:           5

Crystal

Iterative

def factorial(x : Int)    ans = 1    (1..x).each do |i|        ans *= i    end    return ansend

Recursive

def factorial(x : Int)    if x <= 1        return 1    end    return x * factorial(x - 1)end

D

Iterative Version

uint factorial(in uint n) pure nothrow @nogcin {    assert(n <= 12);} body {    uint result = 1;    foreach (immutable i; 1 .. n + 1)        result *= i;    return result;}// Computed and printed at compile-time.pragma(msg, 12.factorial);void main() {    import std.stdio;    // Computed and printed at run-time.    12.factorial.writeln;}
Output:
479001600u479001600

Recursive Version

uint factorial(in uint n) pure nothrow @nogcin {    assert(n <= 12);} body {    if (n == 0)        return 1;    else        return n * factorial(n - 1);}// Computed and printed at compile-time.pragma(msg, 12.factorial);void main() {    import std.stdio;    // Computed and printed at run-time.    12.factorial.writeln;}

(Same output.)

Functional Version

import std.stdio, std.algorithm, std.range;uint factorial(in uint n) pure nothrow @nogcin {    assert(n <= 12);} body {    return reduce!q{a * b}(1u, iota(1, n + 1));}// Computed and printed at compile-time.pragma(msg, 12.factorial);void main() {    // Computed and printed at run-time.    12.factorial.writeln;}

(Same output.)

Tail Recursive (at run-time, with DMD) Version

uint factorial(in uint n) pure nothrowin {    assert(n <= 12);} body {    static uint inner(uint n, uint acc) pure nothrow @nogc {        if (n < 1)            return acc;        else            return inner(n - 1, acc * n);    }    return inner(n, 1);}// Computed and printed at compile-time.pragma(msg, 12.factorial);void main() {    import std.stdio;    // Computed and printed at run-time.    12.factorial.writeln;}

(Same output.)

Dart

Recursive

int fact(int n) {  if(n<0) {    throw new IllegalArgumentException('Argument less than 0');  }  return n==0 ? 1 : n*fact(n-1);}main() {  print(fact(10));  print(fact(-1));}

Iterative

int fact(int n) {  if(n<0) {    throw new IllegalArgumentException('Argument less than 0');  }  int res=1;  for(int i=1;i<=n;i++) {    res*=i;  }  return res;} main() {  print(fact(10));  print(fact(-1));}

dc

This factorial uses tail recursion to iterate fromn down to 2. Some implementations, likeOpenBSD dc, optimize the tail recursion so the call stack never overflows, thoughn might be large.

[* * (n) lfx -- (factorial of n) *]sz[ 1 Sp           [product = 1]sz [              [Loop while 1 < n:]sz  d lp * sp      [product = n * product]sz  1 -            [n = n - 1]sz  d 1 <f ]Sf d 1 <f Lfsz           [Drop loop.]sz sz             [Drop n.]sz Lp             [Push product.]sz]sf[* * For example, print the factorial of 50. *]sz50 lfx psz

Delphi

Iterative

program Factorial1;{$APPTYPE CONSOLE}function FactorialIterative(aNumber: Integer): Int64;var  i: Integer;begin  Result := 1;  for i := 1 to aNumber do    Result := i * Result;end;begin  Writeln('5! = ', FactorialIterative(5));end.

Recursive

program Factorial2;{$APPTYPE CONSOLE}function FactorialRecursive(aNumber: Integer): Int64;begin  if aNumber < 1 then    Result := 1  else    Result := aNumber * FactorialRecursive(aNumber - 1);end;begin  Writeln('5! = ', FactorialRecursive(5));end.

Tail Recursive

program Factorial3;{$APPTYPE CONSOLE}function FactorialTailRecursive(aNumber: Integer): Int64;  function FactorialHelper(aNumber: Integer; aAccumulator: Int64): Int64;  begin    if aNumber = 0 then      Result := aAccumulator    else      Result := FactorialHelper(aNumber - 1, aNumber * aAccumulator);    end;begin  if aNumber < 1 then    Result := 1  else    Result := FactorialHelper(aNumber, 1);end;begin  Writeln('5! = ', FactorialTailRecursive(5));end.

Draco

/* Note that ulong is 32 bits, so fac(12) is the largest * supported value. This is why the input parameter * is a byte. The parameters are all unsigned. */ proc nonrec fac(byte n) ulong:    byte i;    ulong rslt;    rslt := 1;    for i from 2 upto n do        rslt := rslt * i    od;    rsltcorpproc nonrec main() void:    byte i;    for i from 0 upto 12 do        writeln(i:2, "! = ", fac(i):9)    odcorp
Output:
 0! =         1 1! =         1 2! =         2 3! =         6 4! =        24 5! =       120 6! =       720 7! =      5040 8! =     40320 9! =    36288010! =   362880011! =  3991680012! = 479001600

Dragon

select "std"factorial = 1n = readln()for(i=1,i<=n,++i)        {            factorial = factorial * i                 }           showln "factorial of " + n + " is " + factorial

DuckDB

Works with:DuckDB version V1.0

In DuckDB, n! is already defined as the factorial of n, with HUGEINT precision.Here's an equivalent implementation:

create or replace function factorial(n) as (  list_reduce( list_transform(range(1,n+1), x -> x::HUGEINT), (prod,n) -> prod * n));

For a version based on "double" arithmetic:

create or replace function double_precision_factorial(n) as (  list_product( range(1, n+1) ));

Example:

select n, n!, factorial(n), double_precision_factorial(n)from values (4), (30), (33) t(n);
Output:
┌───────┬───────────────────────────────────────┬───────────────────────────────────────┬───────────────────────────────┐│   n   │                ((n)!)                 │             factorial(n)              │ double_precision_factorial(n) ││ int32 │                int128                 │                int128                 │            double             │├───────┼───────────────────────────────────────┼───────────────────────────────────────┼───────────────────────────────┤│     4 │                                    24 │                                    24 │                          24.0 ││    30 │     265252859812191058636308480000000 │     265252859812191058636308480000000 │        2.6525285981219103e+32 ││    33 │ 8683317618811886495518194401280000000 │ 8683317618811886495518194401280000000 │         8.683317618811886e+36 │└───────┴───────────────────────────────────────┴───────────────────────────────────────┴───────────────────────────────┘

DWScript

Note thatFactorial is part of the standard DWScript maths functions.

Iterative

function IterativeFactorial(n : Integer) : Integer;var    i : Integer;begin   Result := 1;   for i := 2 to n do      Result *= i;end;

Recursive

function RecursiveFactorial(n : Integer) : Integer;begin   if n>1 then      Result := RecursiveFactorial(n-1)*n   else Result := 1;end;

Dyalect

func factorial(n) {    if n < 2 {       1    } else {       n * factorial(n - 1)    }}

Dylan

Functional

define method factorial (n)  if (n < 1)    error("invalid argument");  else    reduce1(\*, range(from: 1, to: n))  endend method;

Iterative

define method factorial (n)  if (n < 1)    error("invalid argument");  else    let total = 1;    for (i from n to 2 by -1)      total := total * i;    end;    total  endend method;

Recursive

define method factorial (n)  if (n < 1)    error("invalid argument");  end;  local method loop (n)          if (n <= 2)            n          else            n * loop(n - 1)          end        end;  loop(n)end method;

Tail recursive

define method factorial (n)  if (n < 1)    error("invalid argument");  end;  // Dylan implementations are required to perform tail call optimization so                                                                                                                                                                  // this is equivalent to iteration.                                                                                                                                                                                                         local method loop (n, total)          if (n <= 2)            total          else            let next = n - 1;            loop(next, total * next)          end        end;  loop(n, n)end method;

Déjà Vu

Iterative

factorial:    1    while over:        * over        swap -- swap    drop swap

Recursive

factorial:    if dup:        * factorial -- dup    else:        1 drop

E

pragma.enable("accumulator")def factorial(n) {  return accum 1 for i in 2..n { _ * i }}

EasyLang

func factorial n .   r = 1   for i = 2 to n : r *= i   return r.print factorial 7
Output:
5040

EchoLisp

Iterative

(define (fact n)    (for/product ((f (in-range 2 (1+ n)))) f))(fact 10)    → 3628800

Recursive with memoization

(define (fact n)    (if (zero? n) 1     (* n (fact (1- n)))))(remember 'fact)(fact 10)    → 3628800

Tail recursive

(define (fact n (acc 1))(if (zero? n) acc    (fact (1- n) (* n acc))))(fact 10)    → 3628800

Primitive

(factorial 10)    → 3628800

Numerical approximation

(lib 'math)math.lib v1.13 ® EchoLisp(gamma 11)    → 3628800.0000000005

Ecstasy

module ShowFactorials {    static <Value extends IntNumber> Value factorial(Value n) {        assert:arg n >= Value.zero();        return n <= Value.one() ? n : n * factorial(n-Value.one());    }    @Inject Console console;    void run() {        // 128-bit test        UInt128 bigNum = 34;        console.print($"factorial({bigNum})={factorial(bigNum)}");        // 64-bit test        for (Int i : 10..-1) {            console.print($"factorial({i})={factorial(i)}");        }    }}
Output:
factorial(34)=295232799039604140847618609643520000000factorial(10)=3628800factorial(9)=362880factorial(8)=40320factorial(7)=5040factorial(6)=720factorial(5)=120factorial(4)=24factorial(3)=6factorial(2)=2factorial(1)=1factorial(0)=02023-01-19 10:14:52.716 Service "ShowFactorials" (id=1) at ^ShowFactorials (CallLaterRequest: native), fiber 1: Unhandled exception: IllegalArgument: "n >= Value.zero()": n=-1, Value.zero()=0, Value=Intat factorial(Type<IntNumber>, factorial(?)#Value) (test.x:5)at run() (test.x:19)at ^ShowFactorials (CallLaterRequest: native)

EDSAC order code

[Demo of subroutine to calculate factorial. EDSAC program, Initial Orders 2.][Arrange the storage]          T45K P56F     [H parameter: subroutine for factorial]          T46K P80F     [N parameter: library subroutine P7 to print integer]          T47K P128F    [M parameter: main routine][================================ H parameter ================================]          E25K TH[Subroutine for N factorial. Works for 0 <= N <= 13 (no checking done). Input:  17-bit integer N in 6F (preserved). Output: 35-bit N factorial is returned in 0D. Workspace: 7F]          GK          A3F T19@      [plant return link as usual]          TD            [clear the whole of 0D, including the sandwich bit]          A20@ TF       [0D := 35-bit 1]          A6F T7F       [7F = current factor, initialize to N]          E15@          [jump into middle of loop]       [Head of loop: here with 7F = factor, acc = factor - 2]    [8]   H7F           [mult reg := factor]          A20@          [acc := factor - 1]          T7F           [update factor, clear acc]          VD            [acc := 0D times factor]          L64F L64F     [shift 16 left (as 8 + 8) for integer scaling]          TD            [update product, clear acc]   [15]   A7F S2F       [is factor >= 2 ? (2F permanently holds P1F)]          E8@           [if so, loop back]          T7F           [clear acc on exit]   [19]   ZF            [(planted) return to caller]   [20]   PD            [constant: 17-bit 1][================================ M parameter ================================]          E25K TM GK [Main routine][Teleprinter characters]    [0] K2048F        [1] #F          [letters mode, figures mode]    [2] FF   [3] AF   [4] CF   [5] VF [F, A, C, equals]    [6] !F   [7] @F   [8] &F          [space, carriage return, line feed][Enter here with acc = 0]    [9]   TD            [clear the whole of 0D, including the sandwich bit]          A33@          [load 17-bit number N whose factorial is required]          UF            [store N in 0D, extended to 35 bits for printing]          T6F           [also store N in 6F, for factorial subroutine]          O1@           [set teleprinter to figures]   [14]   A14@ GN       [print N (print subroutine preserves 6F)]       [Print " FAC = " (EDSAC teleprinter had no exclamation mark)]          O@ O6@ O2@ O3@ O4@ O1@ O6@ O5@ O6@   [25]   A25@ GH       [call the above subroutine, 0D := N factorial]   [27]   A27@ GN       [call subroutine to print 0D]          O7@ O8@       [print CR, LF]          O1@           [print dummy character to flush teleprinter buffer]          ZF            [stop]   [33]   P6D           [constant: 17-bit 13][================================ N parameter ================================]          E25K TN [Library subroutine P7, prints long strictly positive integer in 0D. 10 characters, right justified, padded left with spaces. Even address; 35 storage locations; working position 4D.]    GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F    T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@[============================= M parameter again =============================]          E25K TM GK          E9Z           [define entry point]          PF            [acc = 0 on entry][end]
Output:
        13 FAC = 6227020800

EGL

Iterative

function fact(n int in) returns (bigint)    if (n < 0)        writestdout("No negative numbers");        return (0);    end    ans bigint = 1;    for (i int from 1 to n)        ans *= i;    end    return (ans);end

Recursive

function fact(n int in) returns (bigint)    if (n < 0)        SysLib.writeStdout("No negative numbers");        return (0);    end    if (n < 2)    return (1);    else     return (n * fact(n - 1));    endend

Eiffel

notedescription: "recursive and iterative factorial example of a positive integer."classFACTORIAL_EXAMPLEcreatemakefeature -- Initializationmakelocaln: NATURALdon := 5print ("%NFactorial of " + n.out + " = ")print (recursive_factorial (n))endfeature -- Accessrecursive_factorial (n: NATURAL): NATURAL-- factorial of 'n'doif n = 0 thenResult := 1elseResult := n * recursive_factorial (n - 1)endenditerative_factorial (n: NATURAL): NATURAL-- factorial of 'n'localv: like ndofromResult := 1v := nuntilv <= 1loopResult := Result * vv := v - 1endendend

Ela

Tail recursive version:

fact = fact' 1L                    where fact' acc 0 = acc                               fact' acc n = fact' (n * acc) (n - 1)

Elixir

defmodule Factorial do  # Simple recursive function  def fac(0), do: 1  def fac(n) when n > 0, do: n * fac(n - 1)    # Tail recursive function  def fac_tail(0), do: 1  def fac_tail(n), do: fac_tail(n, 1)  def fac_tail(1, acc), do: acc   def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n)  # Tail recursive function with default parameter  def fac_default(n, acc \\ 1)  def fac_default(0, acc), do: acc  def fac_default(n, acc) when n > 0, do: fac_default(n - 1, acc * n)    # Using Enumeration features  def fac_reduce(0), do: 1  def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2)  # Using Enumeration features with pipe operator  def fac_pipe(0), do: 1  def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)end

Elm

Recursive

factorial : Int -> Intfactorial n =  if n < 1 then 1 else n*factorial(n-1)

Tail Recursive

factorialAux : Int -> Int -> IntfactorialAux a acc =    if a < 2 then acc else factorialAux (a - 1) (a * acc)factorial : Int -> Intfactorial a =    factorialAux a 1

Functional

import List exposing (product, range)factorial : Int -> Intfactorial a =    product (range 1 a)

Emacs Lisp

;; Functional (most elegant and best suited to Lisp dialects):(defun fact (n)  "Return the factorial of integer N, which require to be positive or 0."  ;; Elisp won't do any type checking automatically, so  ;; good practice would be doing that ourselves:  (if (not (and (integerp n) (>= n 0)))      (error "Function fact (N): Not a natural number or 0: %S" n))   ;; But the actual code is very short:  (apply '* (number-sequence 1 n)))       ;; (For N = 0, number-sequence returns the empty list, resp. nil,  ;; and the * function works with zero arguments, returning 1.)
;; Recursive:(defun fact (n)  "Return the factorial of integer N, which require to be positive or 0."  (if (not (and (integerp n) (>= n 0))) ; see above      (error "Function fact (N): Not a natural number or 0: %S" n))  (cond ; (or use an (if ...) with an else part)   ((or (= n 0) (= n 1)) 1)    (t (* n (fact (1- n))))))

Both of these only work up to N = 19, beyond which arithmetic overflow seems to happen.Thecalc package (which comes with Emacs) has a builtinfact(). It automatically uses the bignums implemented bycalc.

(require 'calc)(calc-eval "fact(30)")=>"265252859812191058636308480000000"

EMal

fun iterative = int by int n  int result = 1  for int i = 2; i <= n; ++i do result *= i end  return resultendfun recursive = int by int n do return when(n <= 0, 1, n * recursive(n - 1)) endwriteLine("n".padStart(2, " ") + " " + "iterative".padStart(19, " ") + " " + "recursive".padStart(19, " "))for int n = 0; n < 21; ++n  write((text!n).padStart(2, " "))  write(" " + (text!iterative(n)).padStart(19, " "))  write(" " + (text!recursive(n)).padStart(19, " "))  writeLine()end
Output:
 n           iterative           recursive 0                   1                   1 1                   1                   1 2                   2                   2 3                   6                   6 4                  24                  24 5                 120                 120 6                 720                 720 7                5040                5040 8               40320               40320 9              362880              36288010             3628800             362880011            39916800            3991680012           479001600           47900160013          6227020800          622702080014         87178291200         8717829120015       1307674368000       130767436800016      20922789888000      2092278988800017     355687428096000     35568742809600018    6402373705728000    640237370572800019  121645100408832000  12164510040883200020 2432902008176640000 2432902008176640000

embedded C for AVR MCU

Iterative

long factorial(int n) {    long result = 1;    do {         result *= n;    while(--n);    return result;}

Erlang

With a fold:

lists:foldl(fun(X,Y) -> X*Y end, 1, lists:seq(1,N)).

With a recursive function:

fac(1) -> 1;fac(N) -> N * fac(N-1).

With a tail-recursive function:

fac(N) -> fac(N-1,N).fac(1,N) -> N;fac(I,N) -> fac(I-1,N*I).

ERRE

You must use a procedure to implement factorial because ERRE has one-line FUNCTION only.

Iterative procedure:

    PROCEDURE FACTORIAL(X%->F)      F=1      IF X%<>0 THEN        FOR I%=X% TO 2 STEP Ä1 DO          F=F*X%        END FOR      END IF    END PROCEDURE

Recursive procedure:

    PROCEDURE FACTORIAL(FACT,X%->FACT)       IF X%>1 THEN FACTORIAL(X%*FACT,X%-1->FACT)       END IF    END PROCEDURE

Procedure call is for example FACTORIAL(1,5->N)

Euphoria

Straight forward methods

Iterative

function factorial(integer n)  atom f = 1  while n > 1 do    f *= n    n -= 1  end while  return fend function

Recursive

function factorial(integer n)  if n > 1 then    return factorial(n-1) * n  else    return 1  end ifend function

Tail Recursive

Works with:Euphoria version 4.0.0
function factorial(integer n, integer acc = 1)  if n <= 0 then    return acc  else    return factorial(n-1, n*acc)  end ifend function

'Paper tape' / Virtual Machine version

Works with:Euphoria version 4.0.0

Another 'Paper tape' / Virtual Machine version, with as much as possible happening in the tape itself. Some command line handling as well.

include std/mathcons.eenum MUL_LLL, TESTEQ_LIL,TESTLT_LIL,TRUEGO_LL, MOVE_LL, INCR_L, TESTGT_LLL, GOTO_L,OUT_LI,OUT_II,STOPglobal sequence tape = { 1, 1,0,0,0,{TESTLT_LIL, 5, 0, 4},{TRUEGO_LL, 4, 22}, {TESTEQ_LIL, 5, 0, 4},{TRUEGO_LL, 4, 20},{MUL_LLL, 1, 2, 3},{TESTEQ_LIL, 3, PINF, 4},{TRUEGO_LL, 4, 18},{MOVE_LL, 3, 1},{INCR_L, 2},{TESTGT_LLL, 2, 5, 4 },{TRUEGO_LL, 4, 18},{GOTO_L, 10},{OUT_LI, 3, "%.0f\n"},{STOP},{OUT_II, 1, "%.0f\n"},{STOP},{OUT_II, "Negative argument", "%s\n"},{STOP}}global integer ip = 1procedure eval( sequence cmd )atom i = 1while i <= length( cmd ) doswitch cmd[ i ] docase MUL_LLL then -- multiply location location giving locationtape[ cmd[ i + 3 ] ] = tape[ cmd[ i + 1 ] ] * tape[ cmd[ i + 2 ] ]i += 3case TESTEQ_LIL then -- test if location eq value giving locationtape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] )i += 3case TESTLT_LIL then -- test if location eq value giving locationtape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] < cmd[ i + 2 ] )i += 3case TRUEGO_LL then -- if true in location, goto locationif tape[ cmd[ i + 1 ] ] thenip = cmd[ i + 2 ] - 1end ifi += 2case MOVE_LL then -- move value at location to locationtape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ] i += 2case INCR_L then -- increment value at locationtape[ cmd[ i + 1 ] ] += 1i += 1case TESTGT_LLL then -- test if location gt location giving locationtape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] > tape[ cmd[ i + 2 ] ] )i += 3case GOTO_L then -- goto locationip = cmd[ i + 1 ] - 1i += 1case OUT_LI then -- output location using formatprintf( 1, cmd[ i + 2], tape[ cmd[ i + 1 ] ] ) i += 2case OUT_II then -- output immediate using formatif sequence( cmd[ i + 1 ] ) thenprintf( 1, cmd[ i + 2], { cmd[ i + 1 ] } ) elseprintf( 1, cmd[ i + 2], cmd[ i + 1 ] ) end ifi += 2case STOP then -- stopabort(0)end switchi += 1end whileend procedureinclude std/convert.esequence cmd = command_line()if length( cmd ) > 2 thenputs( 1, cmd[ 3 ] & "! = " )tape[ 5 ] = to_number(cmd[3])elseputs( 1, "eui fact.ex <number>\n" )abort(1)end ifwhile 1 doif sequence( tape[ ip ] ) theneval( tape[ ip ] ) end ifip += 1end while

Excel

Choose a cell and write in the function bar on the top :

=fact(5)

The result is shown as :

120

Ezhil

Recursive

நிரல்பாகம்  fact ( n )  @( n == 0 ) ஆனால்            பின்கொடு  1     இல்லை            பின்கொடு    n*fact( n - 1 )    முடிமுடிபதிப்பி fact ( 10 )

F#

//val inline factorial ://   ^a ->  ^a//    when  ^a : (static member get_One : ->  ^a) and//          ^a : (static member ( + ) :  ^a *  ^a ->  ^a) and//          ^a : (static member ( * ) :  ^a *  ^a ->  ^a)let inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]
> factorial 8;;val it : int = 40320> factorial 800I;;val it : bigint = 771053011335386004144639397775028360595556401816010239163410994033970851827093069367090769795539033092647861224230677444659785152639745401480184653174909762504470638274259120173309701702610875092918816846985842150593623718603861642063078834117234098513725265045402523056575658860621238870412640219629971024686826624713383660963127048195572279707711688352620259869140994901287895747290410722496106151954257267396322405556727354786893725785838732404646243357335918597747405776328924775897564519583591354080898117023132762250714057271344110948164029940588827847780442314473200479525138318208302427727803133219305210952507605948994314345449325259594876385922128494560437296428386002940601874072732488897504223793518377180605441783116649708269946061380230531018291930510748665577803014523251797790388615033756544830374909440162270182952303329091720438210637097105616258387051884030288933650309756289188364568672104084185529365727646234588306683493594765274559497543759651733699820639731702116912963247441294200297800087061725868223880865243583365623482704395893652711840735418799773763054887588219943984673401051362280384187818611005035187862707840912942753454646054674870155072495767509778534059298038364204076299048072934501046255175378323008217670731649519955699084482330798811049166276249251326544312580289357812924825898217462848297648349400838815410152872456707653654424335818651136964880049831580548028614922852377435001511377656015730959254647171290930517340367287657007606177675483830521499707873449016844402390203746633086969747680671468541687265823637922007413849118593487710272883164905548707198762911703545119701275432473548172544699118836274377270607420652133092686282081777383674487881628800801928103015832821021286322120460874941697199487758769730544922012389694504960000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000I

Factor

Translation of:Haskell
USING: math.ranges sequences ;: factorial ( n -- n ) [1,b] product ;

The[1,b] word takes a number from the stack and pushes a range, which is then passed toproduct.

FALSE

[1\[$][$@*\1-]#%]f:^'0- f;!.

Recursive:

[$1=~[$1-f;!*]?]f:

Fancy

def class Number {  def factorial {    1 upto: self . product  }}# print first ten factorials1 upto: 10 do_each: |i| {  i to_s ++ "! = " ++ (i factorial) println}

Fantom

The following uses 'Ints' to hold the computed factorials, which limits results to a 64-bit signed integer.

class Main{  static Int factorialRecursive (Int n)  {    if (n <= 1)      return 1    else      return n * (factorialRecursive (n - 1))  }  static Int factorialIterative (Int n)  {    Int product := 1    for (Int i := 2; i <=n ; ++i)    {      product *= i    }    return product  }  static Int factorialFunctional (Int n)  {    (1..n).toList.reduce(1) |a,v|     {       v->mult(a) // use a dynamic invoke      // alternatively, cast a:  v * (Int)a    }  }  public static Void main ()  {    echo (factorialRecursive(20))    echo (factorialIterative(20))    echo (factorialFunctional(20))  }}

Fennel

(do    (fn factorial [n]    ;;; iterative factorial        (if (< n 2)            1        ;else            (do (var f 2)                (for [i 3 n]                     (set f (* f i))                )                f            )        )    )    (for [n 0 10]         (io.write (string.format "%2d! = %s\n" n (factorial n)))    ))
Output:
 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 36288010! = 3628800

Fermat

The factorial function is built in.

666!
Output:
      10106320568407814933908227081298764517575823983241454113404208073574138021 `03697022989202806801491012040989802203557527039339704057130729302834542423840165 `85642874066153029797241068282869939717688434251350949378748077490349338925526287 `83417618832618994264849446571616931313803111176195730515264233203896418054108160 `67607893067483259816815364609828668662748110385603657973284604842078094141556427 `70874534510059882948847250594907196772727091196506088520929434066550648022642608 `33579015030977811408324970137380791127776157191162033175421999994892271447526670 `85796752482688850461263732284539176142365823973696764537603278769322286708855475 `06983568164371084614056976933006577541441308350104365957229945444651724282400214 `05551404642962910019014384146757305529649145692697340385007641405511436428361286 `13304734147348086095123859660926788460671181469216252213374650499557831741950594 `82714722569989641408869425126104519667256749553222882671938160611697400311264211 `15613325735032129607297117819939038774163943817184647655275750142521290402832369 `63922624344456975024058167368431809068544577258472983979437818072648213608650098 `74936976105696120379126536366566469680224519996204004154443821032721047698220334 `84585960930792965695612674094739141241321020558114937361996687885348723217053605 `11305248710796441479213354542583576076596250213454667968837996023273163069094700 `42946710666392541958119313633986054565867362395523193239940480940410876723200000 `00000000000000000000000000000000000000000000000000000000000000000000000000000000 `00000000000000000000000000000000000000000000000000000000000000000000000000000000

FOCAL

1.1 F N=0,10; D 21.2 S N=-3; D 21.3 S N=100; D 21.4 S N=300; D 21.5 Q2.1 I (N)3.1,4.12.2 S R=12.3 F I=1,N; S R=R*I2.4 T "FACTORIAL OF ", %3.0, N, " IS ", %8.0, R, !2.9 R3.1 T "N IS NEGATIVE" !; D 2.94.1 T "FACTORIAL OF     0 IS          1" !; D 2.9
Output:
FACTORIAL OF     0 IS          1FACTORIAL OF =   1 IS =        1FACTORIAL OF =   2 IS =        2FACTORIAL OF =   3 IS =        6FACTORIAL OF =   4 IS =       24FACTORIAL OF =   5 IS =      120FACTORIAL OF =   6 IS =      720FACTORIAL OF =   7 IS =     5040FACTORIAL OF =   8 IS =    40320FACTORIAL OF =   9 IS =   362880FACTORIAL OF =  10 IS =  3628800N IS NEGATIVEFACTORIAL OF = 100 IS = 0.93325720E+158FACTORIAL OF = 300 IS = 0.30605100E+615

The factorial of 300 is the largest one which FOCAL can compute, 301 causes an overflow.

Forth

Single Precision

: fac ( n -- n! ) 1 swap 1+ 1 ?do i * loop ;

Double Precision

On a 64 bit computer, can compute up to 33! Also does error checking. In gforth, error code -24 is "invalid numeric argument."

: factorial ( n -- d )    dup 33 u> -24 and throw    dup 2 < IF        drop 1.    ELSE        1.        rot 1+ 2 DO            i 1 m*/        LOOP    THEN ;33 factorial d. 8683317618811886495518194401280000000  ok-5 factorial d. :2: Invalid numeric argument

Fortran

Fortran 90

A simple one-liner is sufficient.

nfactorial = PRODUCT((/(i, i=1,n)/))

Recursive functions were added in Fortran 90, allowing the following:

INTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS)    INTEGER, INTENT(IN) :: X    IF (X <= 1) THEN        ANS = 1    ELSE        ANS = X * RECURSIVE_FACTORIAL(X-1)    END IFEND FUNCTION RECURSIVE_FACTORIAL

FORTRAN 77

      INTEGER FUNCTION MFACT(N)      INTEGER N,I,FACT      FACT=1      IF (N.EQ.0) GOTO 20      DO 10 I=1,N        FACT=FACT*I10    CONTINUE20    CONTINUE      MFACT = FACT      RETURN      END

friendly interactive shell

Asterisk is quoted to prevent globbing.

Iterative

function factorialset x $argv[1]set result 1for i in (seq $x)set result (expr $i '*' $result)endecho $resultend

Recursive

function factorialset x $argv[1]if [ $x -eq 1 ]echo 1elseexpr (factorial (expr $x - 1)) '*' $xendend

Frink

Frink has a built-in factorial operator and function that creates arbitrarily-large numbers and caches results so that subsequent calls are fast. Some notes on its implementation:

// Calculate factorial with math operatorx = 5println[x!]// Calculate factorial with built-in functionprintln[factorial[x]]

Building a factorial function with no recursion

// Build factorial function with using a range and product function.factorial2[x] := product[1 to x]println[factorial2[5]]

Building a factorial function with recursion

factorial3[x] :={   if x <= 1      return 1   else      return x * factorial3[x-1] // function calling itself}println[factorial3[5]]

FunL

Procedural

def factorial( n ) =  if n < 0    error( 'factorial: n should be non-negative' )  else    res = 1    for i <- 2..n      res *= i    res

Recursive

def  factorial( (0|1) ) = 1  factorial( n )    | n > 0 = n*factorial( n - 1 )    | otherwise = error( 'factorial: n should be non-negative' )

Tail-recursive

def factorial( n )  | n >= 0 =    def      fact( acc, 0 ) = acc      fact( acc, n ) = fact( acc*n, n - 1 )    fact( 1, n )  | otherwise = error( 'factorial: n should be non-negative' )

Using a library function

def factorial( n )  | n >= 0 = product( 1..n )  | otherwise = error( 'factorial: n should be non-negative' )

Futhark

This example isincorrect. Please fix the code and remove this message.

Details: Futhark's syntax has changed, so this example will not compile

Recursive

fun fact(n: int): int =  if n == 0 then 1            else n * fact(n-1)

Iterative

fun fact(n: int): int =  loop (out = 1) = for i < n do    out * (i+1)  in out

FutureBasic

window 1, @"Factorial", ( 0, 0, 300, 550 )local fn factorialIterative( n as long ) as double  double f  long i  if ( n > 1 )    f = 1    for i = 2 to n      f = f * i    next  else    f = 1  end ifend fn = flocal fn factorialRecursive( n as long ) as double  double f  if ( n < 2 )    f = 1  else    f = n * fn factorialRecursive( n -1 )  end ifend fn = flong ifor i = 0 to 12  print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )  print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )  printnextHandleEvents
Output:
Iterative:   0 = 1Recursive:   0 = 1Iterative:   1 = 1Recursive:   1 = 1Iterative:   2 = 2Recursive:   2 = 2Iterative:   3 = 6Recursive:   3 = 6Iterative:   4 = 24Recursive:   4 = 24Iterative:   5 = 120Recursive:   5 = 120Iterative:   6 = 720Recursive:   6 = 720Iterative:   7 = 5040Recursive:   7 = 5040Iterative:   8 = 40320Recursive:   8 = 40320Iterative:   9 = 362880Recursive:   9 = 362880Iterative:  10 = 3628800Recursive:  10 = 3628800Iterative:  11 = 39916800Recursive:  11 = 39916800Iterative:  12 = 479001600Recursive:  12 = 479001600


GAP

# Built-inFactorial(5);# An implementationfact := n -> Product([1 .. n]);

Genyris

def factorial (n)    if (< n 2) 1      * n        factorial (- n 1)

Gleam

Translation of:Erlang

With a fold:

list.fold(int.range(1, n + 1, [], list.prepend), 1, int.multiply)

With a recursive function:

pub fn fac(n: Int) -> Int {  case n {    1 -> 1    n -> n * fac(n - 1)  }}

With a tail-recursive function:

pub fn fac(n: Int) -> Int {  fac_helper(n, n - 1)}fn fac_helper(n: Int, acc: Int) -> Int {  case n, acc {    n, 1 -> n    n, i -> fac_helper(n * i, i - 1)  }}


GML

n = argument0j = 1for(i = 1; i <= n; i += 1)    j *= ireturn j

gnuplot

Gnuplot has a builtin! factorial operator for use on integers.

set xrange [0:4.95]set key leftplot int(x)!

If you wanted to write your own it can be done recursively.

# Using int(n) allows non-integer "n" inputs with the factorial# calculated on int(n) in that case.# Arranging the condition as "n>=2" avoids infinite recursion if# n==NaN, since any comparison involving NaN is false.  Could change# "1" to an expression like "n*0+1" to propagate a NaN input to the# output too, if desired.#factorial(n) = (n >= 2 ? int(n)*factorial(n-1) : 1)set xrange [0:4.95]set key leftplot factorial(x)

Go

Iterative

Sequential, but at least handling big numbers:

package mainimport (    "fmt"    "math/big")func main() {    fmt.Println(factorial(800))}func factorial(n int64) *big.Int {    if n < 0 {        return nil    }    r := big.NewInt(1)    var f big.Int    for i := int64(2); i <= n; i++ {        r.Mul(r, f.SetInt64(i))    }    return r}

Built in, exact

Built in function currently uses a simple divide and conquer technique. It's a step up from sequential multiplication.

package mainimport (    "math/big"    "fmt")func factorial(n int64) *big.Int {    var z big.Int    return z.MulRange(1, n)}func main() {    fmt.Println(factorial(800))}

Efficient exact

For a bigger step up, an algorithm fast enough to compute factorials of numbers up to a million or so, seeFactorial/Go.

Built in, Gamma

package mainimport (    "fmt"    "math")func factorial(n float64) float64 {    return math.Gamma(n + 1)}func main() {    for i := 0.; i <= 10; i++ {        fmt.Println(i, factorial(i))    }    fmt.Println(100, factorial(100))}
Output:
0 11 12 23 64 245 1206 7207 50408 403209 36288010 3.6288e+06100 9.332621544394405e+157

Built in, Lgamma

package mainimport (    "fmt"    "math"    "math/big")func lfactorial(n float64) float64 {    l, _ := math.Lgamma(n + 1)    return l}func factorial(n float64) *big.Float {    i, frac := math.Modf(lfactorial(n) * math.Log2E)    z := big.NewFloat(math.Exp2(frac))    return z.SetMantExp(z, int(i))}func main() {    for i := 0.; i <= 10; i++ {        fmt.Println(i, factorial(i))    }    fmt.Println(100, factorial(100))    fmt.Println(800, factorial(800))}
Output:
0 11 12 23 64 245 119.999999999999946 720.00000000000057 5039.999999999998 40320.0000000000159 362880.000000000110 3.6288000000000084e+06100 9.332621544394454e+157800 7.710530113351238e+1976

Golfscript

Iterative (uses folding)

{.!{1}{,{)}%{*}*}if}:fact;5fact puts # test

or

{),(;{*}*}:fact;

Recursive

{.1<{;1}{.(fact*}if}:fact;

Gridscript

#FACTORIAL.@width 14@height 8(1,3):START(7,1):CHECKPOINT 0(3,3):INPUT INT TO n(5,3):STORE n(7,3):GO EAST(9,3):DECREMENT n(11,3):SWITCH n(11,5):MULTIPLY BY n(11,7):GOTO 0(13,3):PRINT

Groovy

Recursive

A recursive closure must bepre-declared.

def rFactrFact = { (it > 1) ? it * rFact(it - 1) : 1 as BigInteger }

Iterative

def iFact = { (it > 1) ? (2..it).inject(1 as BigInteger) { i, j -> i*j } : 1 }

Test Program:

def time = { Closure c ->    def start = System.currentTimeMillis()    def result = c()    def elapsedMS = (System.currentTimeMillis() - start)/1000    printf '(%6.4fs elapsed)', elapsedMS    result}def dashes = '---------------------'print "   n!       elapsed time   "; (0..15).each { def length = Math.max(it - 3, 3); printf " %${length}d", it }; println()print "--------- -----------------"; (0..15).each { def length = Math.max(it - 3, 3); print " ${dashes[0..<length]}" }; println()[recursive:rFact, iterative:iFact].each { name, fact ->    printf "%9s ", name    def factList = time { (0..15).collect {fact(it)} }    factList.each { printf ' %3d', it }    println()}
Output:
   n!       elapsed time      0   1   2   3   4   5   6    7     8      9      10       11        12         13          14           15--------- ----------------- --- --- --- --- --- --- --- ---- ----- ------ ------- -------- --------- ---------- ----------- ------------recursive (0.0040s elapsed)   1   1   2   6  24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000iterative (0.0060s elapsed)   1   1   2   6  24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000

Guish

Recursive

fact = {    if eq(@1, 0) {        return 1    } else {        return mul(@1, fact(sub(@1, 1)))    }}puts fact(7)

Tail recursive

fact = {    if eq(@1, 1) {        return @2    }    return fact(sub(@1, 1), mul(@1, @2))}puts fact(7, 1)

Haskell

The simplest description: factorial is the product of the numbers from 1 to n:

factorial n = product [1..n]

Or, using composition and omitting the argument (partial application):

factorial = product . enumFromTo 1

Or, written explicitly as a fold:

factorial n = foldl (*) 1 [1..n]

See also:The Evolution of a Haskell Programmer

Or, if you wanted to generate a list of all the factorials:

factorials = scanl (*) 1 [1..]
factorials = 1 : zipWith (*) factorials [1..]
factorials = go 1 1 where    go n fac = f : go (n+1) (n*fac)


Or, written without library functions:

factorial :: Integral -> Integralfactorial 0 = 1factorial n = n * factorial (n-1)

Tail-recursive, checking the negative case:

fac n    | n >= 0    = go 1 n    | otherwise = error "Negative factorial!"        where go acc 0 = acc              go acc n = go (acc * n) (n - 1)

Using postfix notation:

{-# LANGUAGE PostfixOperators #-}(!) :: Integer -> Integer(!) 0 = 1(!) n = n * (pred n !)main :: IO ()main = do  print (5 !)  print ((4 !) !)


Binary splitting

The following method is more efficient for large numbers.

-- product of [a,a+1..b]productFromTo a b =   if a>b then 1   else if a == b then a   else productFromTo a c * productFromTo (c+1) b   where c = (a+b) `div` 2factorial = productFromTo 1

Haxe

Iterative

static function factorial(n:Int):Int {  var result = 1;  while (1<n)    result *= n--;  return result;}

Recursive

static function factorial(n:Int):Int {  return n == 0 ? 1 : n * factorial2(n - 1);}

Tail-Recursive

inline static function _fac_aux(n, acc:Int):Int {  return n < 1 ? acc : _fac_aux(n - 1, acc * n);}static function factorial(n:Int):Int {  return _fac_aux(n,1);}

Functional

static function factorial(n:Int):Int {  return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);}

Comparison

using StringTools;using Lambda;class Factorial {  // iterative  static function factorial1(n:Int):Int {    var result = 1;    while (1<n)      result *= n--;    return result;  }  // recursive  static function factorial2(n:Int):Int {    return n == 0 ? 1 : n * factorial2(n - 1);  }  // tail-recursive  inline static function _fac_aux(n, acc:Int):Int {    return n < 1 ? acc : _fac_aux(n - 1, acc * n);  }  static function factorial3(n:Int):Int {    return _fac_aux(n,1);  }  // functional   static function factorial4(n:Int):Int {    return [for (i in 1...(n+1)) i].fold(function(num, total) return total *= num, 1);  }  static function main() {    var v = 12;    // iterative    var start = haxe.Timer.stamp();    var result = factorial1(v);    var duration = haxe.Timer.stamp() - start;    Sys.println('iterative'.rpad(' ', 20) + 'result: $result time: $duration ms');    // recursive    start = haxe.Timer.stamp();    result = factorial2(v);    duration = haxe.Timer.stamp() - start;    Sys.println('recursive'.rpad(' ', 20) + 'result: $result time: $duration ms');    // tail-recursive    start = haxe.Timer.stamp();    result = factorial3(v);    duration = haxe.Timer.stamp() - start;    Sys.println('tail-recursive'.rpad(' ', 20) + 'result: $result time: $duration ms');    // functional    start = haxe.Timer.stamp();    result = factorial4(v);    duration = haxe.Timer.stamp() - start;    Sys.println('functional'.rpad(' ', 20) + 'result: $result time: $duration ms');  }}
Output:
iterative           result: 479001600 time: 6.198883056640625e-06 msrecursive           result: 479001600 time: 1.31130218505859375e-05 mstail-recursive      result: 479001600 time: 1.9073486328125e-06 msfunctional          result: 479001600 time: 1.40666961669921875e-05 ms

hexiscript

Iterative

fun fac n  let acc 1  while n > 0    let acc (acc * n--)  endwhile  return accendfun

Recursive

fun fac n  if n <= 0    return 1  else     return n * fac (n - 1)  endifendfun

HicEst

WRITE(Clipboard) factorial(6)  ! pasted: 720FUNCTION factorial(n)   factorial = 1   DO i = 2, n      factorial = factorial * i   ENDDOEND

Hobbes

Recursive

factorial :: int -> intfactorial n = if (n == 0) then 1 else n * factorial(n - 1)
Output:
> factorial(10)3628800

HolyC

Iterative

U64 Factorial(U64 n) {  U64 i, result = 1;  for (i = 1; i <= n; ++i)    result *= i;  return result;}Print("1:  %d\n", Factorial(1));Print("10: %d\n", Factorial(10));

Note: Does not support negative numbers.

Recursive

I64 Factorial(I64 n) {  if (n == 0)    return 1;  if (n < 0)    return -1 * ((-1 * n) * Factorial((-1 * n) - 1));  return n * Factorial(n - 1));}Print("+1:  %d\n", Factorial(1));Print("+10: %d\n", Factorial(10));Print("-10: %d\n", Factorial(-10));

Hy

(defn ! [n]  (reduce *    (range 1 (inc n))    1))(print (! 6))  ; 720(print (! 0))  ; 1

i

concept factorial(n) {return n!} software {print(factorial(-23))print(factorial(0))print(factorial(1))print(factorial(2))print(factorial(3))print(factorial(22))}

Icon andUnicon

Recursive

procedure factorial(n)        n := integer(n) | runerr(101, n)   if n < 0 then fail   return if n = 0 then 1 else n*factorial(n-1)end

Iterative

The

Library:Icon Programming Library

factors provides the following iterative procedure which can be included with 'link factors':

procedure factorial(n)#: return n! (n factorial)   local i   n := integer(n) | runerr(101, n)   if n < 0 then fail   i := 1   every i *:= 1 to n   return iend

IDL

function fact,n   return, product(lindgen(n)+1)end

Inform 6

[ factorial n;    if (n == 0)        return 1;    else        return n * factorial(n - 1);];

Insitux

Translation of:Clojure

Iterative

(function factorial n  (... *1 (range 2 (inc n))))

Recursive

(function factorial x  (if (< x 2)      1      (*1 x (factorial (dec x)))))

Io

Factorials are built-in to Io:

3 factorial

J

Operator

  ! 8             NB.  Built in factorial operator40320

Iterative / Functional

   */1+i.840320

Recursive

  (*$:@:<:)^:(1&<) 840320

Generalization

Factorial, like most of J's primitives, is generalized (mathematical generalization is often something to avoid in application code while being something of a curated virtue in utility code):

  ! 8 0.8 _0.8    NB.  Generalizes as 1 + the gamma function40320 0.931384 4.59084  ! 800x          NB.  Also arbitrarily large7710530113353860041446393977750283605955564018160102391634109940339708518270930693670907697955390330926478612242306774446597851526397454014801846531749097625044706382742591201733097017026108750929188168469858421505936237186038616420630788341172340985137252...

Jakt

fn factorial(anon n: i64) throws -> i64 {    if n < 0 {        throw Error::from_string_literal("Factorial's operand must be non-negative")    }    mut result = 1    for i in 1..(n + 1) {        result *= i    }    return result}fn main() {    for i in 0..11 {        println("{} factorial is {}", i, factorial(i))    }}

Janet

Recursive

Non-Tail Recursive

(defn factorial [x]    (cond        (< x 0) nil        (= x 0) 1        (* x (factorial (dec x)))))

Tail Recursive

Given the initial recursive sample is not using tail recursion, there is a possibility to hit a stack overflow (if the user has lowered Janet's very high default max stack size) or exhaust the host's available memory.

The recursive sample can be written with tail recursion (Janet supports TCO) to perform the algorithm in linear time and constant space, instead of linear space.

(defn factorial-iter [product counter max-count]  (if (> counter max-count)    product    (factorial-iter (* counter product) (inc counter) max-count)))(defn factorial [n]  (factorial-iter 1 1 n))

Iterative

(defn factorial [x]    (cond        (< x 0) nil        (= x 0) 1        (do            (var fac 1)            (for i 1 (inc x)                (*= fac i))            fac)))

Functional

(defn factorial [x]    (cond        (< x 0) nil        (= x 0) 1        (product (range 1 (inc x)))))

Java

Iterative

package programas;import java.math.BigInteger;import java.util.InputMismatchException;import java.util.Scanner;public class IterativeFactorial {  public BigInteger factorial(BigInteger n) {    if ( n == null ) {      throw new IllegalArgumentException();    }    else if ( n.signum() == - 1 ) {      // negative      throw new IllegalArgumentException("Argument must be a non-negative integer");    }    else {      BigInteger factorial = BigInteger.ONE;      for ( BigInteger i = BigInteger.ONE; i.compareTo(n) < 1; i = i.add(BigInteger.ONE) ) {        factorial = factorial.multiply(i);      }      return factorial;    }  }  public static void main(String[] args) {    Scanner scanner = new Scanner(System.in);    BigInteger number, result;    boolean error = false;    System.out.println("FACTORIAL OF A NUMBER");    do {      System.out.println("Enter a number:");      try {        number = scanner.nextBigInteger();        result = new IterativeFactorial().factorial(number);        error = false;        System.out.println("Factorial of " + number + ": " + result);      }      catch ( InputMismatchException e ) {        error = true;        scanner.nextLine();      }      catch ( IllegalArgumentException e ) {        error = true;        scanner.nextLine();      }    }    while ( error );    scanner.close();  }}

Recursive

package programas;import java.math.BigInteger;import java.util.InputMismatchException;import java.util.Scanner;public class RecursiveFactorial {  public BigInteger factorial(BigInteger n) {    if ( n == null ) {      throw new IllegalArgumentException();    }    else if ( n.equals(BigInteger.ZERO) ) {      return BigInteger.ONE;    }    else if ( n.signum() == - 1 ) {      // negative      throw new IllegalArgumentException("Argument must be a non-negative integer");    }    else {      return n.equals(BigInteger.ONE)          ? BigInteger.ONE          : factorial(n.subtract(BigInteger.ONE)).multiply(n);    }  }  public static void main(String[] args) {    Scanner scanner = new Scanner(System.in);    BigInteger number, result;    boolean error = false;    System.out.println("FACTORIAL OF A NUMBER");    do {      System.out.println("Enter a number:");      try {        number = scanner.nextBigInteger();        result = new RecursiveFactorial().factorial(number);        error = false;        System.out.println("Factorial of " + number + ": " + result);      }      catch ( InputMismatchException e ) {        error = true;        scanner.nextLine();      }      catch ( IllegalArgumentException e ) {        error = true;        scanner.nextLine();      }    }    while ( error );    scanner.close();  }}

Simplified and Combined Version

import java.math.BigInteger;import java.util.InputMismatchException;import java.util.Scanner;public class LargeFactorial {    public static long userInput;    public static void main(String[]args){        Scanner input = new Scanner(System.in);        System.out.println("Input factorial integer base: ");        try {            userInput = input.nextLong();            System.out.println(userInput + "! is\n" + factorial(userInput) + " using standard factorial method.");            System.out.println(userInput + "! is\n" + factorialRec(userInput) + " using recursion method.");        }catch(InputMismatchException x){            System.out.println("Please give integral numbers.");        }catch(StackOverflowError ex){            if(userInput > 0) {                System.out.println("Number too big.");            }else{                System.out.println("Please give non-negative(positive) numbers.");            }        }finally {            System.exit(0);        }    }    public static BigInteger factorialRec(long n){        BigInteger result = BigInteger.ONE;        return n == 0 ? result : result.multiply(BigInteger.valueOf(n)).multiply(factorial(n-1));    }    public static BigInteger factorial(long n){        BigInteger result = BigInteger.ONE;        for(int i = 1; i <= n; i++){            result = result.multiply(BigInteger.valueOf(i));        }        return result;    }}

Using Java 9

import java.math.BigInteger;import java.util.function.Function;import java.util.stream.LongStream;import java.util.stream.Stream;public final class Factorial {public static void main(String[] args) {// Valid only for integer arguments 1, 2, ... , 20Function<Integer, Long> factorialPositive = n -> LongStream.rangeClosed(2, n).reduce(1, (a, b) -> a * b);// Valid for integer arguments <= 20Function<Integer, Long> factorial = n -> {if ( n < 0 || n > 20 ) {throw new AssertionError("Argument is out of range: " + n);}return factorialPositive.apply(n);};// Return a BigInteger valueFunction<Integer, BigInteger> factorialBig = n -> Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE))                                                .limit(n)                                                .reduce(BigInteger.ONE, BigInteger::multiply);}}

JavaScript

Iterative

function factorial(n) {  //check our edge case  if (n < 0) { throw "Number must be non-negative"; }  var result = 1;  //we skip zero and one since both are 1 and are identity  while (n > 1) {    result *= n;    n--;  }  return result;}

Recursive

ES5 (memoized )

(function(x) {  var memo = {};  function factorial(n) {    return n < 2 ? 1 : memo[n] || (memo[n] = n * factorial(n - 1));  }    return factorial(x);  })(18);
Output:
6402373705728000

Or, assuming that we have some sort of integer range function, we can memoize using the accumulator of a fold/reduce:

(function () {    'use strict';    // factorial :: Int -> Int    function factorial(x) {        return range(1, x)            .reduce(function (a, b) {                return a * b;            }, 1);    }    // range :: Int -> Int -> [Int]    function range(m, n) {        var a = Array(n - m + 1),            i = n + 1;        while (i-- > m) a[i - m] = i;        return a;    }    return factorial(18);})();
Output:
6402373705728000


ES6

var factorial = n => (n < 2) ? 1 : n * factorial(n - 1);


Or, as an alternative to recursion, we can fold/reduce a product function over the range of integers 1..n

(() => {    'use strict';    // factorial :: Int -> Int    const factorial = n =>        enumFromTo(1, n)        .reduce(product, 1);    const test = () =>        factorial(18);    // --> 6402373705728000    // GENERIC FUNCTIONS ----------------------------------    // product :: Num -> Num -> Num    const product = (a, b) => a * b;    // range :: Int -> Int -> [Int]    const enumFromTo = (m, n) =>        Array.from({            length: (n - m) + 1        }, (_, i) => m + i);    // MAIN ------    return test();})();
Output:
6402373705728000


The first part outputs the factorial for every addition to the array and the second part calculates factorial from a single number.

<html>  <body>    <button>Factorial</button>    <p></p>    <p></p>    <br>      </body></html><input value=""><br><button>Single Value Factorial</button><p></p><p></p><script>  function mathFact(total, sum) {    return total * sum;  }  var incNumbers = [1];  function incrementFact() {    var n = incNumbers.pop();    incNumbers.push(n);    incNumbers.push(n + 1);    document.getElementById("FactArray").innerHTML = incNumbers;    document.getElementById("Factorial").innerHTML = incNumbers.reduceRight(mathFact);  }  var singleNum = [];  function singleFact() {    var x = document.getElementById("userInput").value;    for (i = 0; i < x; i++) {      singleNum.push(i + 1);      document.getElementById("SingleFactArray").innerHTML = singleNum;    }    document.getElementById("SingleFactorial").innerHTML = singleNum.reduceRight(mathFact);    singleNum = [];  }</script>

JOVIAL

PROC FACTORIAL(ARG) U;    BEGIN    ITEM ARG U;    ITEM TEMP U;    TEMP = 1;    FOR I:2 BY 1 WHILE I<=ARG;        TEMP = TEMP*I;    FACTORIAL = TEMP;    END

Joy

<

DEFINE ! == [1] [*] primrec.6!.

jq

An efficient and idiomatic definition in jq is simply to multiply the first n integers:

def fact:  reduce range(1; .+1) as $i (1; . * $i);

Here is a rendition in jq of the standard recursive definition of the factorial function, assuming n is non-negative:

def fact(n):  if n <= 1 then n  else n * fact(n-1)  end;

Recent versions of jq support tail recursion optimization for 0-arity filters, so here is an implementation that would benefit from this optimization. The helper function,_fact, is defined here as a subfunction of the main function, which is a filter that accepts the value of n from its input.

def fact:  def _fact:    # Input: [accumulator, counter]    if .[1] <= 1 then .    else [.[0] * .[1], .[1] - 1]|  _fact    end;   # Extract the accumulated value from the output of _fact:  [1, .] | _fact | .[0] ;

Jsish

/* Factorial, in Jsish *//* recursive */function fact(n) { return ((n < 2) ? 1 : n * fact(n - 1)); }/* iterative */function factorial(n:number) {    if (n < 0) throw format("factorial undefined for negative values: %d", n);    var fac = 1;    while (n > 1) fac *= n--;    return fac;}if (Interp.conf('unitTest') > 0) {;fact(18);;fact(1);;factorial(18);;factorial(42);try { factorial(-1); } catch (err) { puts(err); }}
Output:
prompt$ jsish --U factorial.jsifact(18) ==> 6402373705728000fact(1) ==> 1factorial(18) ==> 6402373705728000factorial(42) ==> 1.40500611775288e+51factorial undefined for negative values: -1

Julia

Works with:Julia version 0.6

Built-in version:

help?> factorialsearch: factorial Factorization factorize  factorial(n)  Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at  least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n))  to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is  equivalent to gamma(n+1).  julia> factorial(6)  720  julia> factorial(21)  ERROR: OverflowError()  [...]  julia> factorial(21.0)  5.109094217170944e19  julia> factorial(big(21))  51090942171709440000

Dynamic version:

function fact(n::Integer)    n < 0 && return zero(n)    f = one(n)    for i in 2:n        f *= i    end    return fendfor i in 10:20println("$i -> ", fact(i))end
Output:
10 -> 362880011 -> 3991680012 -> 47900160013 -> 622702080014 -> 8717829120015 -> 130767436800016 -> 2092278988800017 -> 35568742809600018 -> 640237370572800019 -> 12164510040883200020 -> 2432902008176640000

Alternative version:

fact2(n::Integer) = prod(Base.OneTo(n))@show fact2(20)
Output:
fact2(20) = 2432902008176640000

K

Iterative

  facti:*/1+!:  facti 5120

Recursive

  factr:{:[x>1;x*_f x-1;1]}  factr 6720

Klingphix

{ recursive }:factorial    dup 1 great (    [dup 1 - factorial *]    [drop 1]    ) if; { iterative }:factorial2    1 swap [*] for; ( 0 22 ) [    "Factorial(" print dup print ") = " print factorial2 print nl] for" " input
Output:
Factorial(0) = 1Factorial(1) = 1Factorial(2) = 2Factorial(3) = 6Factorial(4) = 24Factorial(5) = 120Factorial(6) = 720Factorial(7) = 5040Factorial(8) = 40320Factorial(9) = 362880Factorial(10) = 3628800Factorial(11) = 39916800Factorial(12) = 479001600Factorial(13) = 6.22703e+9Factorial(14) = 8.71783e+10Factorial(15) = 1.30768e+12Factorial(16) = 2.09228e+13Factorial(17) = 3.55688e+14Factorial(18) = 6.40238e+15Factorial(19) = 1.21646e+17Factorial(20) = 2.4329e+18Factorial(21) = 5.1091e+19Factorial(22) = 1.124e+21

Klong

Based on the K examples above.

    factRecursive::{:[x>1;x*.f(x-1);1]}    factIterative::{*/1+!x}

KonsolScript

function factorial(Number n):Number {  Var:Number ret;  if (n >= 0) {    ret = 1;    Var:Number i = 1;    for (i = 1; i <= n; i++) {      ret = ret * i;    }  } else {    ret = 0;  }  return ret;}

Kotlin

fun facti(n: Int) = when {    n < 0 -> throw IllegalArgumentException("negative numbers not allowed")    else  -> {        var ans = 1L        for (i in 2..n) ans *= i        ans    }}fun factr(n: Int): Long = when {    n < 0 -> throw IllegalArgumentException("negative numbers not allowed")    n < 2 -> 1L    else  -> n * factr(n - 1)}fun main(args: Array<String>) {    val n = 20    println("$n! = " + facti(n))    println("$n! = " + factr(n))}
Output:
20! = 243290200817664000020! = 2432902008176640000

Lambda Calculus

Church encoded numerals

FACT = ^nf.n (^ra.a (r (^fx.f (a f x)))) (^a.f) (^h.h);; FACT n f x = 1 (2 (3 ... (n f) ...)) x = (1*2*3*...*n)(f)(x)

Development:

0 = ^fx. x 1 = ^fx. f x SUCC = ^mfx. f (m f x) ADD  = ^nmfx. n f (m f x)  = ^nmfx. n SUCC m f xSUB  = ^nmfx. n PRED m f xMULT = ^nmfx. n (m f) x POW  = ^bnfx. n b f x PRED = ^nfx. n (^ri. i (r f)) (^f. x) (^a. a)    HALF = ^nfx. n (^rij. i (r j i)) (^ji. x) (^a. a) f;; iteration: (MULT n (MULT ... (MULT 2 (MULT 1 1)) ...))FACT1 = ^n. n (^rai. r (MULT i a) (SUCC i)) (^ai. a) 1 1 ;; recursion: (MULT 1 (MULT 2 (MULT ... (MULT n 1) ...)))FACT2 = ^n. n (^ra. MULT a (r (SUCC a))) (^a. 1) 1;;            (^raf. a (r (SUCC a) f));; direct code creation: (1 (2 (... (n f) ...))) xFACT = ^nfx. n (^ra. a (r (SUCC a))) (^a. f) 1 x;; calculation:FACT (SUCC (SUCC 1)) f x;; => 1 (2 (3 ((^a. f) 4))) x;; =>    2 (3       f  )  x;; => 3 f     (3 f     x  );; => f (f (f (f (f (f x)))))

Church lists are right folds over the list's elements,[a,b,c] g z = g a (g b (g c z)) ; MAP f l g z = l (^a. g (f a)) z. Church numerals areunary encodings, folds over lists of unimportant, indiscernible values, like[(),(),()], where the list's length represents the number, and the increment functionf is the partial application of a folding function,g ().

There's natural correspondence of functions for the two types, with similar implementations,

ADD     <--->   APPENDSUCC    <--->   CONS0       <--->   NIL ISZERO  <--->   ISEMPTYPRED    <--->   TAILMULT    <--->   CARTESIAN_PRODUCTMIN     <--->   ZIP (or MAP2)

Scott encoding

Scott encoding usually entails directly using general recursion, pattern-matching case switching and continuation handling style:

0 = ^zs.z1 = ^zs.s 0SUCC = ^uzs.s uPRED = ^m.m 0 (^u.u) = ^mzs.m z (^u.u z s);; PRED 0 z s = z = 0 z s;; PRED (SUCC u) z s = SUCC u z (^u.u z s) = (^u.u z s) u = u z stoChurch = ^mfx. (^g.g g m) (^gi. i x (^u. f (g g u))) fromChurch = ^m. m SUCC 0 = ^m. m (^uzs.s u) (^zs.z)ADD  = ^ij. toChurch j SUCC   iMULT = ^ij. toChurch j (ADD i) 0EXPT = ^ij. toChurch j (MULT i) 1FACT = ^i. toChurch i (^ri. MULT i (r (SUCC i))) (^i. 1) 1

It's also possible to define a more general looping facility, with the looping function being given access to thecurrent value in addition to the recursive result,

LOOP = ^xfm. (^g.g g m) (^gi. i x (^u. f i (g g u)))  ;; LOOP x f m =  f m (f (m-1) (... (f 1 x) ...))

were the factorial fits right in,

FACT =     LOOP 1 MULT                ; i!   = i*(i-1)*(i-2)*...*1*1ADD  = ^i. LOOP i (^m. SUCC)          ; i+j  = (SUCC^j)(i)MULT = ^i. LOOP 0 (^m. ADD i)         ; i*j  = ((ADD i)^j)(0)EXPT = ^i. LOOP 1 (^m. MULT i)        ; i**j = ((MULT i)^j)(1)toChurch = ^mfx. LOOP x (^m. f) mLOOP = ^xfm. toChurch m (^rm. f m (r (PRED m))) (^m. x) m

Or, usingY combinator,

LOOP = ^xfm. Y (^ri. i x (^u. f i (r u))) m;; LOOP x f m =  f m (f (m-1) (... (f 1 x) ...));; derivation:LOOP = ^xfm. (^g.g g m) (^gi. i x (^u. f i (g g u)))     =  ^xf. (^g.g g)   (^gi. i x (^u. f i (g g u)))     =  ^xf. U    (^g.  (^ri. i x (^u. f i (r   u)))  (g g))     =  ^xf. (^s. U (^g. s (g g))) (^ri. i x (^u. f i (r u)))     =  ^xf. Y (^ri. i x (^u. f i (r u)))  ;; rec = Y step          = step (Y step)          = step rec ;; rec = H step (H step) = step (H step (H step)) = step rec ;;       H s    (H s   ) = s    (H s    (H s   ));;       H s     g       = s    (g       g      );; U g = g g;; Y s = U (H s);; Y s = U (^g. s (g g))      ;; g g = s (g g);; rec = U (^g. step (g g))   ;; g g = step (g g)

Lambdatalk

{def fac {lambda {:n}  {if {< :n 1}   then 1   else {long_mult :n {fac {- :n 1}}}}}}{fac 6}-> 720{fac 100}-> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Lang

Iterative

fp.fact = ($n) -> {if($n < 0) {throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)}$ret = 1L$i = 2while($i <= $n) {$ret *= $i$i += 1}return $ret}

Recursive

fp.fact = ($n) -> {if($n < 0) {throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)}elif($n < 2) {return 1L}return parser.op($n * fp.fact(-|$n))}

Array Reduce

fp.fact = ($n) -> {if($n < 0) {throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)}return fn.arrayReduce(fn.arrayGenerateFrom(fn.inc, $n), 1L, fn.mul)}

Lang5

Folding

  : fact iota 1 + '* reduce ;  5 fact120

Recursive

  : fact dup 2 < if else dup 1 - fact * then ;  5 fact120

langur

Folding

val factorial = fn n: fold(2 .. n, by=fn{*})writeln factorial(7)

Recursive

val factorial = fn x: if(x < 2: 1; x * fn((x - 1)))writeln factorial(7)

Iterative

val factorial = fn(i) {    var answer = 1    for x in 2 .. i {       answer *= x    }    answer}writeln factorial(7)

Iterative Folding

val factorial = fn n: for[=1] x in n { _for *= x }writeln factorial(7)
Output:
5040

Lasso

Iterative

define factorial(n) => {  local(x = 1)  with i in generateSeries(2, #n)  do {    #x *= #i  }  return #x}

Recursive

define factorial(n) => #n < 2 ? 1 | #n * factorial(#n - 1)

Latitude

Functional

factorial := {  1 upto ($1 + 1) product.}.

Recursive

factorial := {  takes '[n].  if { n == 0. } then {    1.  } else {    n * factorial (n - 1).  }.}.

Iterative

factorial := {  local 'acc = 1.  1 upto ($1 + 1) do {    acc = acc * $1.  }.  acc.}.

LDPL

data:n is numberprocedure:sub factorial    parameters:        n is number        result is number    local data:        i is number        m is number    procedure:        store 1 in result        in m solve n + 1        for i from 1 to m step 1 do            multiply result by i in result        repeatend subcreate statement "get factorial of $ in $" executing factorialget factorial of 5 in ndisplay n lf
Output:
120

Lean

def factorial (n : Nat) : Nat :=  match n with  | 0 => 1  | (k + 1) => (k + 1) * factorial (k)

LFE

Non-Tail-Recursive Versions

The non-tail-recursive versions of this function are easy to read: they look like the math textbook definitions. However, they will cause the Erlang VM to throw memory errors when passed very large numbers. To avoid such errors, use the tail-recursive version below.

Using thecondform:

(defun factorial (n)  (cond    ((== n 0) 1)    ((> n 0) (* n (factorial (- n 1))))))

Using guards (with thewhenform):

(defun factorial  ((n) (when (== n 0)) 1)  ((n) (when (> n 0))    (* n (factorial (- n 1)))))

Using pattern matching and a guard:

(defun factorial  ((0) 1)  ((n) (when (> n 0))    (* n (factorial (- n 1)))))

Tail-Recursive Version

(defun factorial (n)  (factorial n 1))(defun factorial  ((0 acc) acc)  ((n acc) (when (> n 0))    (factorial (- n 1) (* n acc))))

Example usage in the REPL:

> (lists:map #'factorial/1 (lists:seq 10 20))(3628800 39916800 479001600 6227020800 87178291200 1307674368000 20922789888000 355687428096000 6402373705728000 121645100408832000 2432902008176640000)

Or, usingio:format to print results tostdout:

> (lists:foreach    (lambda (x)      (io:format '"~p~n" `(,(factorial x))))    (lists:seq 10 20))36288003991680047900160062270208008717829120013076743680002092278988800035568742809600064023737057280001216451004088320002432902008176640000ok

Note that the use ofprogn above was simply to avoid the list ofoks that are generated as a result of callingio:format inside alists:map's anonymous function.

Lingo

Recursive

on fact (n)  if n<=1 then return 1  return n * fact(n-1)end

Iterative

on fact (n)  res = 1  repeat with i = 2 to n    res = res*i  end repeat  return resend

Lisaac

- factorial x : INTEGER : INTEGER <- (  + result : INTEGER;  (x <= 1).if {    result := 1;  } else {    result := x * factorial(x - 1);  };  result);

Little Man Computer

The Little Man can cope with integers up to 999. So he can calculate up to 6 factorial before it all gets too much for him.

// Little Man Computer// Reads an integer n and prints n factorial// Works for n = 0..6        LDA one    // initialize factorial to 1        STA fac        INP        // get n from user        BRZ done   // if n = 0, return 1        STA n      // else store n        LDA one    // initialize k = 1outer   STA k      // outer loop: store latest k        LDA n      // test for k = n        SUB k        BRZ done   // done if so        LDA fac    // save previous factorial        STA prev        LDA k      // initialize i = kinner   STA i      // inner loop: store latest i        LDA fac    // build factorial by repeated addition        ADD prev        STA fac        LDA i      // decrement i        SUB one        BRZ next_k // if i = 0, move on to next k        BRA inner  // else loop for another additionnext_k  LDA k      // increment k        ADD one           BRA outer  // back to start of outer loop  done    LDA fac    // done, load the result        OUT        // print it        HLT        // haltn       DAT 0      // input valuek       DAT 0      // outer loop counter, 1 up to ni       DAT 0      // inner loop counter, k down to 0fac     DAT 0      // holds k!, i.e. n! when doneprev    DAT 0      // previous value of facone     DAT 1      // constant 1// end


LiveCode

// recursivefunction factorialr n    if n < 2 then         return 1    else        return n * factorialr(n-1)    end ifend factorialr// using accumulatorfunction factorialacc n acc    if n = 0 then        return acc    else        return factorialacc(n-1, n * acc)    end ifend factorialaccfunction factorial n    return factorialacc(n,1)end factorial// iterativefunction factorialit nput 1 into f    if n > 1 then         repeat with i = 1 to n            multiply f by i        end repeat    end if    return fend factorialit

LLVM

; ModuleID = 'factorial.c'; source_filename = "factorial.c"; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; target triple = "x86_64-pc-windows-msvc19.21.27702"; This is not strictly LLVM, as it uses the C library function "printf".; LLVM does not provide a way to print values, so the alternative would be; to just load the string into memory, and that would be boring.; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps$"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = comdat any@"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1;--- The declaration for the external C printf function.declare i32 @printf(i8*, ...); Function Attrs: noinline nounwind optnone uwtabledefine i32 @factorial(i32) #0 {;-- local copy of n  %2 = alloca i32, align 4;-- long result  %3 = alloca i32, align 4;-- int i  %4 = alloca i32, align 4;-- local n = parameter n  store i32 %0, i32* %2, align 4;-- result = 1  store i32 1, i32* %3, align 4;-- i = 1  store i32 1, i32* %4, align 4  br label %looploop:;-- i <= n  %5 = load i32, i32* %4, align 4  %6 = load i32, i32* %2, align 4  %7 = icmp sle i32 %5, %6  br i1 %7, label %loop_body, label %exitloop_body:;-- result *= i  %8 = load i32, i32* %4, align 4  %9 = load i32, i32* %3, align 4  %10 = mul nsw i32 %9, %8  store i32 %10, i32* %3, align 4  br label %loop_incrementloop_increment:;-- ++i  %11 = load i32, i32* %4, align 4  %12 = add nsw i32 %11, 1  store i32 %12, i32* %4, align 4  br label %loopexit:;-- return result  %13 = load i32, i32* %3, align 4  ret i32 %13}; Function Attrs: noinline nounwind optnone uwtabledefine i32 @main() #0 {;-- factorial(5)  %1 = call i32 @factorial(i32 5);-- printf("%ld\n", factorial(5))  %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01??_C@_04PEDNGLFL@?$CFld?6?$AA@", i32 0, i32 0), i32 %1);-- return 0  ret i32 0}attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }!llvm.module.flags = !{!0, !1}!llvm.ident = !{!2}!0 = !{i32 1, !"wchar_size", i32 2}!1 = !{i32 7, !"PIC Level", i32 2}!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}
Output:
120

Logo

Recursive

to factorial :n  if :n < 2 [output 1]  output :n * factorial :n-1end

Iterative

NOTE: Slight code modifications may needed in order to run this as each Logo implementation differs in various ways.

to factorial :n make "fact 1 make "i 1 repeat :n [make "fact :fact * :i make "i :i + 1] print :fact end

LOLCODE

HAI 1.3HOW IZ I Faktorial YR Number  BOTH SAEM 1 AN BIGGR OF Number AN 1   O RLY?   YA RLY    FOUND YR 1   NO WAI    FOUND YR PRODUKT OF Number AN I IZ Faktorial YR DIFFRENCE OF Number AN 1 MKAY  OICIF U SAY SOIM IN YR Loop UPPIN YR Index WILE DIFFRINT Index AN 13  VISIBLE Index "! = " I IZ Faktorial YR Index MKAYIM OUTTA YR LoopKTHXBYE
Output:
0! = 11! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 362880011! = 3991680012! = 479001600

Lua

Recursive

function fact(n)  return n > 0 and n * fact(n-1) or 1end

Tail Recursive

function fact(n, acc)  acc = acc or 1  if n == 0 then    return acc  end  return fact(n-1, n*acc)end

Memoization

The memoization table can be accessed directly (eg.fact[10]) and will return the memoized value,ornil if the value has not been memoized yet.

If called as a function (eg.fact(10)), the value will be calculated, memoized and returned.

fact = setmetatable({[0] = 1}, {  __call = function(t,n)    if n < 0 then return 0 end    if not t[n] then t[n] = n * t(n-1) end    return t[n]  end})

M2000 Interpreter

Using Decimal type

M2000 Interpreter running in M2000 Environment, a Visual Basic 6.0 application. So we use Decimals, for output.

Normal Print overwrite console screen, and at the last line scroll up on line, feeding a new clear line. Some time needed to print over and we wish to erase the line before doing that. Here we use another aspect of this variant of Print. Any special formatting function $() are kept local, so after the end of statement formatting return to whatever has before.

We want here to change width of column. Normally column width for all columns are the same. For this statement (Print Over) this not hold, we can change column width as print with it. Also we can change justification, and we can choose on column the use of proportional or non proportional text rendering (console use any font as non proportional by default, and if it is proportional font then we can use it as proportional too). Because no new line append to end of this statement, we need to use a normal Print to send new line.

1@ is 1 in Decimal type (27 digits).

Module CheckIt {      Locale 1033 ' ensure #,### print with comma      Function factorial (n){            If n<0 then Error "Factorial Error!"            If n>27 then Error "Overflow"                        m=1@:While n>1 {m*=n:n--}:=m      }      Const Proportional=4      Const ProportionalLeftJustification=5      Const NonProportional=0      Const NonProportionalLeftJustification=1      For i=1 to 27       \\ we can print over (erasing line first), without new line at the end      \\ and we can change how numbers apears, and the with of columns      \\ numbers by default have right justification      \\ all $() format have temporary use in this kind of print.      Print Over $(Proportional),$("\f\a\c\t\o\r\i\a\l\(#\)\=",15), i, $(ProportionalLeftJustification), $("#,###",40), factorial(i)      Print        \\ new line      Next i}Checkit
Output:
                factorial(1)= 1                factorial(2)= 2                factorial(3)= 6                factorial(4)= 24                factorial(5)= 120                factorial(6)= 720                factorial(7)= 5,040                factorial(8)= 40,320                factorial(9)= 362,880               factorial(10)= 3,628,800               factorial(11)= 39,916,800               factorial(12)= 479,001,600               factorial(13)= 6,227,020,800               factorial(14)= 87,178,291,200               factorial(15)= 1,307,674,368,000               factorial(16)= 20,922,789,888,000               factorial(17)= 355,687,428,096,000               factorial(18)= 6,402,373,705,728,000               factorial(19)= 121,645,100,408,832,000               factorial(20)= 2,432,902,008,176,640,000               factorial(21)= 51,090,942,171,709,440,000               factorial(22)= 1,124,000,727,777,607,680,000               factorial(23)= 25,852,016,738,884,976,640,000               factorial(24)= 620,448,401,733,239,439,360,000               factorial(25)= 15,511,210,043,330,985,984,000,000               factorial(26)= 403,291,461,126,605,635,584,000,000               factorial(27)= 10,888,869,450,418,352,160,768,000,000

Using BigInteger

Cls , 0  ' 0 for non split display, eg 3 means we preserve the 3 top lines from scrolling/claReport {Factorial TaskDefinitions               • The factorial of   0   (zero)   is defined as being   1   (unity).               • The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence:                                                                      n,   n-1,   n-2,   ...   1                                                                       }Cls, row  ' now we preserve some lines (as row number return here)Module CheckIt {m=1u   ' 1u is bigintegerk=width-tab  For i=1 to 1000 if pos>tab then printm*=i     Print @(0), format$("{0::-4} :", i);Report str$(m), k' Report accumulate lines and stop at 3/4 of the screen (but not on printer)' so we can break this using this line: while inkey$<>"": wait 1:end while: keyboard " "Next i}Checkit
!000th Factorial

M4

define(`factorial',`ifelse(`$1',0,1,`eval($1*factorial(decr($1)))')')dnldnlfactorial(5)
Output:
120

MAD

            NORMAL MODE IS INTEGER                     R   CALCULATE FACTORIAL OF N             INTERNAL FUNCTION(N)            ENTRY TO FACT.            RES = 1            THROUGH FACMUL, FOR MUL = 2, 1, MUL.G.NFACMUL      RES = RES * MUL            FUNCTION RETURN RES            END OF FUNCTION                     R   USE THE FUNCTION TO PRINT 0! THROUGH 12!            VECTOR VALUES FMT = $I2,6H ! IS ,I9*$            THROUGH PRNFAC, FOR NUM = 0, 1, NUM.G.12PRNFAC      PRINT FORMAT FMT, NUM, FACT.(NUM)            END OF PROGRAM
Output:
 0! IS         1 1! IS         1 2! IS         2 3! IS         6 4! IS        24 5! IS       120 6! IS       720 7! IS      5040 8! IS     40320 9! IS    36288010! IS   362880011! IS  3991680012! IS 479001600

MANOOL

Recursive version, MANOOLish “cascading” notation:

{ let rec  { Fact = -- compile-time constant binding    { proc { N } as -- precondition: N.IsI48[] & (N >= 0)    : if N == 0 then 1 else      N * Fact[N - 1]    }  }  in -- use Fact here or just make the whole expression to evaluate to it:  Fact}

Conventional notation (equivalent to the above up to AST):

{ let rec  { Fact = -- compile-time constant binding    { proc { N } as -- precondition: N.IsI48[] & (N >= 0)      { if N == 0 then 1 else        N * Fact[N - 1]      }    }  }  in -- use Fact here or just make the whole expression to evaluate to it:  Fact}

Iterative version (in MANOOL, probably more appropriate in this particular case):

{ let  { Fact = -- compile-time constant binding    { proc { N } as -- precondition: N.IsI48[] & (N >= 0)    : var { Res = 1 } in -- variable binding    : do Res after -- return result    : while N <> 0 do -- loop while N does not equal to zero      Res = N * Res; N = N - 1    }  }  in -- use Fact here or just make the whole expression to evaluate to it:  Fact}

Maple

Builtin

> 5!;                                  120

Recursive

RecFact := proc( n :: nonnegint )        if n = 0 or n = 1 then                1        else                n * thisproc( n -  1 )        end ifend proc:
> seq( RecFact( i ) = i!, i = 0 .. 10 );1 = 1, 1 = 1, 2 = 2, 6 = 6, 24 = 24, 120 = 120, 720 = 720, 5040 = 5040,    40320 = 40320, 362880 = 362880, 3628800 = 3628800

Iterative

IterFact := proc( n :: nonnegint )        local   i;        mul( i, i = 2 .. n )end proc:
> seq( IterFact( i ) = i!, i = 0 .. 10 );1 = 1, 1 = 1, 2 = 2, 6 = 6, 24 = 24, 120 = 120, 720 = 720, 5040 = 5040,    40320 = 40320, 362880 = 362880, 3628800 = 3628800

Mathematica /Wolfram Language

Note that Mathematica already comes with a factorial function, which can be used as e.g.5! (gives 120). So the following implementations are only of pedagogical value.

Recursive

factorial[n_Integer] := n*factorial[n-1]factorial[0] = 1

Iterative (direct loop)

factorial[n_Integer] :=   Block[{i, result = 1}, For[i = 1, i <= n, ++i, result *= i]; result]

Iterative (list)

factorial[n_Integer] := Block[{i}, Times @@ Table[i, {i, n}]]

MATLAB

Built-in

The factorial function is built-in to MATLAB. The built-in function is only accurate for N <= 21 due to the precision limitations of floating point numbers.

answer = factorial(N)

Recursive

function f=fac(n)    if n==0        f=1;        return    else        f=n*fac(n-1);    end

Iterative

A possible iterative solution:

  function b=factorial(a)b=1;for i=1:a    b=b*i;end

Maude

fmod FACTORIAL isprotecting INT .op undefined : -> Int .op _! : Int -> Int .var n : Int .eq 0 ! = 1 .eq n ! = if n < 0 then undefined else n * (sd(n, 1) !) fi .endfmred 11 ! .

Maxima

Built-in

n!

Recursive

fact(n) := if n < 2 then 1 else n * fact(n - 1)$

Iterative

fact2(n) := block([r: 1], for i thru n do r: r * i, r)$

MAXScript

Iterative

fn factorial n =(    if n == 0 then return 1    local fac = 1    for i in 1 to n do    (        fac *= i    )    fac)

Recursive

fn factorial_rec n =(    local fac = 1    if n > 1 then    (        fac = n * factorial_rec (n - 1)    )    fac)

Mercury

Recursive (using arbitrary large integers and memoisation)

:- module factorial.:- interface.:- import_module integer.:- func factorial(integer) = integer.:- implementation.:- pragma memo(factorial/1).factorial(N) =    (   N =< integer(0)    ->  integer(1)    ;   factorial(N - integer(1)) * N    ).

A small test program:

:- module test_factorial.:- interface.:- import_module io.:- pred main(io::di, io::uo) is det.:- implementation.:- import_module factorial.:- import_module char, integer, list, string.main(!IO) :-    command_line_arguments(Args, !IO),    filter(is_all_digits, Args, CleanArgs),    Arg1 = list.det_index0(CleanArgs, 0),    Number = integer.det_from_string(Arg1),    Result = factorial(Number),    Fmt = integer.to_string,    io.format("factorial(%s) = %s\n", [s(Fmt(Number)), s(Fmt(Result))], !IO).

Example output:

factorial(100) = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

min

Works with:min version 0.19.6
((dup 0 ==) 'succ (dup pred) '* linrec) :factorial

MiniScript

Iterative

factorial = function(n)    result = 1    for i in range(2,n)        result = result * i    end for    return resultend functionprint factorial(10)

Recursive

factorial = function(n)     if n <= 0 then return 1 else return n * factorial(n-1)end functionprint factorial(10)
Output:
3628800

MiniZinc

var int: factorial(int: n) =  let {    array[0..n] of var int: factorial;    constraint forall(a in 0..n)(      factorial[a] == if (a == 0) then        1      else        a*factorial[a-1]      endif  )} in factorial[n];var int: fac = factorial(6);solve satisfy;output [show(fac),"\n"];

MIPS Assembly

Iterative

################################### Factorial; iterative           ## By Keith Stellyes :)           ## Targets Mars implementation    ## August 24, 2016                #################################### This example reads an integer from user, stores in register a1# Then, it uses a0 as a multiplier and target, it is set to 1# Pseudocode:# a0 = 1# a1 = read_int_from_user()# while(a1 > 1)# {# a0 = a0*a1# DECREMENT a1# }# print(a0).text ### PROGRAM BEGIN ###### GET INTEGER FROM USER ###li $v0, 5 #set syscall arg to READ_INTEGERsyscall #make the syscallmove $a1, $v0 #int from READ_INTEGER is returned in $v0, but we need $v0              #this will be used as a counter### SET $a1 TO INITAL VALUE OF 1 AS MULTIPLIER ###li $a0,1### Multiply our multiplier, $a1 by our counter, $a0 then store in $a1 ###loop:ble $a1,1,exit # If the counter is greater than 1, go back to startmul $a0,$a0,$a1 #a1 = a1*a0subi $a1,$a1,1 # Decrement counterj loop # Go back to startexit: ### PRINT RESULT ###li $v0,1 #set syscall arg to PRINT_INTEGER#NOTE: syscall 1 (PRINT_INTEGER) takes a0 as its argument. Conveniently, that#      is our result. syscall  #make the syscall#exitli $v0, 10 #set syscall arg to EXITsyscall #make the syscall

Recursive

#reference code#int factorialRec(int n){#    if(n<2){return 1;}#    else{ return n*factorial(n-1);}#}.datan:.word 5result:.word.textmain:la$t0, nlw$a0, 0($t0)jalfactorialRecla$t0, resultsw$v0, 0($t0)addi$v0, $0, 10syscallfactorialRec:addi$sp, $sp, -8#calling conventionsw$a0, 0($sp)sw$ra, 4($sp)addi$t0, $0, 2#if (n < 2) do return 1 slt$t0, $a0, $t0#else return n*factorialRec(n-1)beqz$t0, anotherCalllw$ra, 4($sp)#recursive anchorlw$a0, 0($sp)addi$sp, $sp, 8addi$v0, $0, 1jr$raanotherCall:addi$a0, $a0, -1jalfactorialReclw$ra, 4($sp)lw$a0, 0($sp)addi$sp, $sp, 8mul$v0, $a0, $v0jr$ra

Mirah

def factorial_iterative(n:int)    2.upto(n-1) do |i|        n *= i     end    nendputs factorial_iterative 10

МК-61/52

ВПП01ИП0*L003С/П

ML/I

Iterative

MCSKIP "WITH" NL"" Factorial - iterativeMCSKIP MT,<>MCINS %.MCDEF FACTORIAL WITHS ()AS <MCSET T1=%A1.MCSET T2=1MCSET T3=1%L1.MCGO L2 IF T3 GR T1MCSET T2=T2*T3MCSET T3=T3+1MCGO L1%L2.%T2.>fact(1) is FACTORIAL(1)fact(2) is FACTORIAL(2)fact(3) is FACTORIAL(3)fact(4) is FACTORIAL(4)

Recursive

MCSKIP "WITH" NL"" Factorial - recursiveMCSKIP MT,<>MCINS %.MCDEF FACTORIAL WITHS ()AS <MCSET T1=%A1.MCGO L1 UNLESS T1 EN 01<>MCGO L0%L1.%%T1.*FACTORIAL(%T1.-1).>fact(1) is FACTORIAL(1)fact(2) is FACTORIAL(2)fact(3) is FACTORIAL(3)fact(4) is FACTORIAL(4)

mn

(  (n) let  1 (product) let  (n 1 >=)  (    product n * (product) bind    n 1 - (n) bind  ) while  product) (factorial) lambda5 factorial puts pop
Output:
120

Modula-2

MODULE Factorial;FROM FormatString IMPORT FormatString;FROM Terminal IMPORT WriteString,ReadChar;PROCEDURE Factorial(n : CARDINAL) : CARDINAL;VAR result : CARDINAL;BEGIN    result := 1;    WHILE n#0 DO        result := result * n;        DEC(n)    END;    RETURN resultEND Factorial;VAR    buf : ARRAY[0..63] OF CHAR;    n : CARDINAL;BEGIN    FOR n:=0 TO 10 DO        FormatString("%2c! = %7c\n", buf, n, Factorial(n));        WriteString(buf)    END;    ReadCharEND Factorial.

Modula-3

Iterative

PROCEDURE FactIter(n: CARDINAL): CARDINAL =  VAR    result := n;    counter := n - 1;      BEGIN    FOR i := counter TO 1 BY -1 DO      result := result * i;    END;    RETURN result;  END FactIter;

Recursive

PROCEDURE FactRec(n: CARDINAL): CARDINAL =  VAR result := 1;  BEGIN    IF n > 1 THEN      result := n * FactRec(n - 1);    END;    RETURN result;  END FactRec;

Mouse

Mouse 79

"PRIME NUMBERS!" N1 = (NN. 1 + = #P,N.; )$P F1 = N1 =   ( FF . 1 + = %AF. - ^ %AF./F. * %A - 1 + [N0 = 0 ^ ] )     N. [ %A! "!" ] @$$

MUMPS

Iterative

factorial(num)New ii,resultIf num<0 Quit "Negative number"If num["." Quit "Not an integer"Set result=1 For ii=1:1:num Set result=result*iiQuit resultWrite $$factorial(0) ; 1Write $$factorial(1) ; 1Write $$factorial(2) ; 2Write $$factorial(3) ; 6Write $$factorial(10) ; 3628800Write $$factorial(-6) ; Negative numberWrite $$factorial(3.7) ; Not an integer

Recursive

factorial(num);If num<0 Quit "Negative number"If num["." Quit "Not an integer"If num<2 Quit 1Quit num*$$factorial(num-1)Write $$factorial(0) ; 1Write $$factorial(1) ; 1Write $$factorial(2) ; 2Write $$factorial(3) ; 6Write $$factorial(10) ; 3628800Write $$factorial(-6) ; Negative numberWrite $$factorial(3.7) ; Not an integer

MyrtleScript

func factorial args: int a : returns: int {    int factorial = a    repeat int i = (a - 1) : i == 0 : i-- {        factorial *= i    }    return factorial}

Nanoquery

Translation of:Python
def factorial(n)        result = 1for i in range(1, n)                result = result * i        end        return resultend

Neko

var factorial = function(number) {var i = 1;var result = 1;while(i <= number) {result *= i;i += 1;}return result;};$print(factorial(10));

Nemerle

Here's two functional programming ways to do this and an iterative example translated from the C# above. Usinglong, we can only usenumber <= 20, I just don't like the scientific notation output from using adouble. Note that in the iterative example, variables whose values change are explicitly defined as mutable; the default in Nemerle is immutable values, encouraging a more functional approach.

using System;using System.Console;module Program{  Main() : void  {      WriteLine("Factorial of which number?");      def number = long.Parse(ReadLine());      WriteLine("Using Fold : Factorial of {0} is {1}", number, FactorialFold(number));      WriteLine("Using Match: Factorial of {0} is {1}", number, FactorialMatch(number));      WriteLine("Iterative  : Factorial of {0} is {1}", number, FactorialIter(number));  }    FactorialFold(number : long) : long  {      $[1L..number].FoldLeft(1L, _ * _ )  }    FactorialMatch(number : long) : long  {      |0L => 1L      |n  => n * FactorialMatch(n - 1L)  }    FactorialIter(number : long) : long  {      mutable accumulator = 1L;      for (mutable factor = 1L; factor <= number; factor++)      {          accumulator *= factor;      }      accumulator  //implicit return  }}

NetRexx

/* NetRexx */options replace format comments java crossref savelog symbols nobinarynumeric digits 64 -- switch to exponential format when numbers become larger than 64 digitssay 'Input a number: \-'saydo  n_ = long ask -- Gets the number, must be an integer  say n_'! =' factorial(n_) '(using iteration)'  say n_'! =' factorial(n_, 'r') '(using recursion)'  catch ex = Exception    ex.printStackTraceendreturnmethod factorial(n_ = long, fmethod = 'I') public static returns Rexx signals IllegalArgumentException  if n_ < 0 then -    signal IllegalArgumentException('Sorry, but' n_ 'is not a positive integer')  select    when fmethod.upper = 'R' then -      fact = factorialRecursive(n_)    otherwise -      fact = factorialIterative(n_)    end  return factmethod factorialIterative(n_ = long) private static returns Rexx  fact = 1  loop i_ = 1 to n_    fact = fact * i_    end i_  return factmethod factorialRecursive(n_ = long) private static returns Rexx  if n_ > 1 then -    fact = n_ * factorialRecursive(n_ - 1)  else -   fact = 1  return fact
Output:
Input a number: 4949! = 608281864034267560872252163321295376887552831379210240000000000 (using iteration)49! = 608281864034267560872252163321295376887552831379210240000000000 (using recursion)

newLISP

> (define (factorial n) (exp (gammaln (+ n 1))))(lambda (n) (exp (gammaln (+ n 1))))> (factorial 4)24

Nial

(from Nial help file)

fact is recur [ 0 =, 1 first, pass, product, -1 +]

Using it

|fact 4=24

Nickle

Factorial is a built-in operator in Nickle. To more correctly satisfy the task, it is wrapped in a function here, but does not need to be. Inputs of 1 or below, return 1.

int fact(int n) { return n!; }
Output:
prompt$ nickle> load "fact.5c"> fact(66)544344939077443064003729240247842752644293064388798874532860126869671081148416000000000000000> fact(-5)1> -5!-120> fact(1.1)Unhandled exception invalid_argument ("Incompatible argument", 0, 1.1)<stdin>:11:     fact ((11/10));

Note the precedence of factorial before negation, (-5)! is 1 in Nickle, -5! is the negation of 5!, -120.

Also note how the input of 1.1 is internally managed as 11/10 in the error message.

Nim

Library

import mathlet i:int = fac(x)

Recursive

proc factorial(x): int =  if x > 0: x * factorial(x - 1)  else: 1

Iterative

proc factorial(x: int): int =  result = 1  for i in 2..x:    result *= i

Niue

Recursive

[ dup 1 > [ dup 1 - factorial * ] when ] 'factorial ;( test )4 factorial . ( => 24 )10 factorial . ( => 3628800 )

Nu

def 'math factorial' [] {[$in 1] | math max | 1..$in | math product}..10 | each {math factorial}
Output:
╭────┬─────────╮│  0 │       1 ││  1 │       1 ││  2 │       2 ││  3 │       6 ││  4 │      24 ││  5 │     120 ││  6 │     720 ││  7 │    5040 ││  8 │   40320 ││  9 │  362880 ││ 10 │ 3628800 │╰────┴─────────╯

Nyquist

Lisp Syntax

Iterative:

(defun factorial (n)  (do ((x n (* x n)))      ((= n 1) x)    (setq n (1- n))))

Recursive:

(defun factorial (n)  (if (= n 1)      1      (* n (factorial (1- n)))))

Oberon-2

Works with:oo2c
MODULE Factorial;IMPORT  Out;VAR   i: INTEGER;  PROCEDURE Iterative(n: LONGINT): LONGINT;  VAR    i, r: LONGINT;  BEGIN    ASSERT(n >= 0);    r := 1;    FOR i := n TO 2 BY -1 DO      r := r * i    END;    RETURN r  END Iterative;  PROCEDURE Recursive(n: LONGINT): LONGINT;  VAR    r: LONGINT;  BEGIN    ASSERT(n >= 0);    r := 1;    IF n > 1 THEN       r := n * Recursive(n - 1)    END;    RETURN r  END Recursive;BEGIN  FOR i := 0 TO 9 DO    Out.String("Iterative ");Out.Int(i,0);Out.String('! =');Out.Int(Iterative(i),0);Out.Ln;  END;  Out.Ln;  FOR i := 0 TO 9 DO    Out.String("Recursive ");Out.Int(i,0);Out.String('! =');Out.Int(Recursive(i),0);Out.Ln;  ENDEND Factorial.
Output:
Iterative 0! =1Iterative 1! =1Iterative 2! =2Iterative 3! =6Iterative 4! =24Iterative 5! =120Iterative 6! =720Iterative 7! =5040Iterative 8! =40320Iterative 9! =362880Recursive 0! =1Recursive 1! =1Recursive 2! =2Recursive 3! =6Recursive 4! =24Recursive 5! =120Recursive 6! =720Recursive 7! =5040Recursive 8! =40320Recursive 9! =362880

Oberon-07

Almost identical to the Oberon-2 sample, with minor output formatting differences.
Oberon-2 allows single or double quotes to delimit strings whereas Oberon-07 only allows double quotes. Also, the LONGINT type does not exist in Oberon-07 (though some compilers may accept is as a synonym for INTEGER).

MODULE Factorial;IMPORT  Out;VAR   i: INTEGER;  PROCEDURE Iterative(n: INTEGER): INTEGER;  VAR    i, r: INTEGER;  BEGIN    ASSERT(n >= 0);    r := 1;    FOR i := n TO 2 BY -1 DO      r := r * i    END;    RETURN r  END Iterative;  PROCEDURE Recursive(n: INTEGER): INTEGER;  VAR    r: INTEGER;  BEGIN    ASSERT(n >= 0);    r := 1;    IF n > 1 THEN       r := n * Recursive(n - 1)    END;    RETURN r  END Recursive;BEGIN  FOR i := 0 TO 9 DO    Out.String("Iterative ");Out.Int(i,0);Out.String("! =");Out.Int(Iterative(i),8);Out.Ln;  END;  Out.Ln;  FOR i := 0 TO 9 DO    Out.String("Recursive ");Out.Int(i,0);Out.String("! =");Out.Int(Recursive(i),8);Out.Ln;  ENDEND Factorial.
Output:
Iterative 0! =       1Iterative 1! =       1Iterative 2! =       2Iterative 3! =       6Iterative 4! =      24Iterative 5! =     120Iterative 6! =     720Iterative 7! =    5040Iterative 8! =   40320Iterative 9! =  362880Recursive 0! =       1Recursive 1! =       1Recursive 2! =       2Recursive 3! =       6Recursive 4! =      24Recursive 5! =     120Recursive 6! =     720Recursive 7! =    5040Recursive 8! =   40320Recursive 9! =  362880

Objeck

Iterative

bundle Default {  class Fact {    function : Main(args : String[]) ~ Nil {      5->Factorial()->PrintLine();    }  }}

OCaml

Recursive

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

The following is tail-recursive, so it is effectively iterative:

let factorial n =  let rec loop i accum =    if i > n then accum    else loop (i + 1) (accum * i)  in loop 1 1

Iterative

It can be done using explicit state, but this is usually discouraged in a functional language:

let factorial n =  let result = ref 1 in  for i = 1 to n do    result := !result * i  done;  !result

Bignums

All of the previous examples use normal OCaml ints, so on a 64-bit platform the factorial of 100 will be equal to 0, rather than to a 158-digit number.

The following code uses the Zarith package to calculate the factorials of larger numbers:

let rec factorial n =  let rec loop acc = function    | 0 -> acc    | n -> loop (Z.mul (Z.of_int n) acc) (n - 1)  in loop Z.one nlet () =  if not !Sys.interactive then    begin      Sys.argv.(1) |> int_of_string |> factorial |> Z.print;      print_newline ()    end
Output:
$ ocamlfind ocamlopt -package zarith zarith.cmxa fact.ml -o fact$ ./fact 10093326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Octave

% built in factorialprintf("%d\n", factorial(50));% let's define our recursive...function fact = my_fact(n)  if ( n <= 1 )    fact = 1;  else    fact = n * my_fact(n-1);  endifendfunctionprintf("%d\n", my_fact(50));% let's define our iterativefunction fact = iter_fact(n)  fact = 1;  for i = 2:n    fact = fact * i;  endforendfunctionprintf("%d\n", iter_fact(50));
Output:
304140932017130189699674576664359451329578820634579911320168038403041409320171337557636696640674798683205706483651478717955728998430414093201713375576366966406747986832057064836514787179557289984

(Built-in is fast but use an approximation for big numbers)

Suggested correction: Neither of the three (two) results above is exact. The exact result (computed with Haskell) should be:

30414093201713378043612608166064768844377641568960512000000000000

In fact, all results given by Octave are precise up to their 16th digit, the rest seems to be "random" in all cases. Apparently, this is a consequence of Octave not being capable of arbitrary precision operation.

Odin

package mainfactorial :: proc(n: int) -> int {  return 1 if n == 0 else n * factorial(n - 1)}factorial_iterative :: proc(n: int) -> int {  result := 1  for i in 2..=n do result *= i  return result}main :: proc() {  assert(factorial(4) == 24)  assert(factorial_iterative(4) == 24)}

Oforth

Recursive :

: fact(n)  n ifZero: [ 1 ] else: [ n n 1- fact * ] ;

Imperative :

: fact | i | 1 swap loop: i [ i * ] ;
Output:
>50 fact .s[1] (Integer) 30414093201713378043612608166064768844377641568960512000000000000ok

Order

Simple recursion:

#include <order/interpreter.h>#define ORDER_PP_DEF_8fac                     \ORDER_PP_FN(8fn(8N,                           \                8if(8less_eq(8N, 0),          \                    1,                        \                    8mul(8N, 8fac(8dec(8N))))))ORDER_PP(8to_lit(8fac(8)))    // 40320

Tail recursion:

#include <order/interpreter.h>#define ORDER_PP_DEF_8fac                                                                         \ORDER_PP_FN(8fn(8N,                                                                               \                8let((8F, 8fn(8I, 8A, 8G,                                                         \                              8if(8greater(8I, 8N),                                               \                                  8A,                                                             \                                  8apply(8G, 8seq_to_tuple(8seq(8inc(8I), 8mul(8A, 8I), 8G)))))), \                      8apply(8F, 8seq_to_tuple(8seq(1, 1, 8F))))))ORDER_PP(8to_lit(8fac(8)))    // 40320

Oz

Folding

fun {Fac1 N}   {FoldL {List.number 1 N 1} Number.'*' 1}end

Tail recursive

fun {Fac2 N}   fun {Loop N Acc}      if N < 1 then Acc      else {Loop N-1 N*Acc}      end   endin   {Loop N 1}end

Iterative

fun {Fac3 N}   Result = {NewCell 1}in   for I in 1..N do      Result := @Result * I   end   @Resultend

Panda

fun fac(n) type integer->integer  product{{1..n}}1..10.fac

PARI/GP

All of these versions include bignum support. The recursive version is limited by the operating system's stack size; it may not be able to compute factorials larger than twenty thousand digits. The gamma function method is reliant on precision; to use it for large numbers increasedefault(realprecision) as needed.

Recursive

fact(n)=if(n<2,1,n*fact(n-1))

Iterative

This is an improvement on the naive recursion above, being faster and not limited by stack space.

fact(n)=my(p=1);for(k=2,n,p*=k);p

Binary splitting

PARI'sfactorback automatically uses binary splitting, preventing subproducts from growing overly large. This function is dramatically faster than the above.

fact(n)=factorback([2..n])

Recursive 1

Even faster

f( a, b )={ my(c);if( b == a, return(a));if( b-a > 1,c=(b + a) >> 1;return(f(a, c) * f(c+1, b)));return( a * b );}fact(n) = f(1, n)

Built-in

Uses binary splitting. According to the source, this was found to be faster than prime decomposition methods. This is, of course, faster than the above.

fact(n)=n!

Gamma

Note also the presence offactorial andlngamma.

fact(n)=round(gamma(n+1))

Moessner's algorithm

Not practical, just amusing. Note the lack of* or^. A variant of an algorithm presented in

Alfred Moessner, "Eine Bemerkung über die Potenzen der natürlichen Zahlen."S.-B. Math.-Nat. Kl. Bayer. Akad. Wiss.29:3 (1952).

This is very slow but should be able to compute factorials until it runs out of memory (usage is aboutn2logn{\displaystyle {\displaystyle n^{2}\log n}} bits to compute n!); a machine with 1 GB of RAM and unlimited time could, in theory, find 100,000-digit factorials.

fact(n)={  my(v=vector(n+1,i,i==1));  for(i=2,n+1,    forstep(j=i,2,-1,      for(k=2,j,v[k]+=v[k-1])    )  );  v[n+1]};

Pascal

Iterative

function factorial(n: integer): integer; var  i, result: integer; begin  result := 1;  for i := 2 to n do   result := result * i;  factorial := result end;

Iterative FreePascal

{$mode objFPC}{R+}FUNCTION Fact(n: qword): qword;VAR    F: qword;BEGIN    if n > 20 then    begin        WriteLn('This function is only accurate up to 20!');        exit(0);    end;    asm        (*) Initialize result = 1 (0! = 1 case handled automatically) (*)        mov     $1, %rax          (*)  RAX = 1 (initial result)       (*)        mov      n, %rcx          (*)  RCX = input number (counter)   (*)        test    %rcx, %rcx        (*)  Check if n=0                   (*)        jz      .Lstore_result    (*)  Skip loop if n=0               (*)    .Lloop1:        imul    %rcx, %rax        (*)  RAX = RAX * RCX (signed mul)   (*)        dec     %rcx              (*)  Decrement RCX                  (*)        jnz     .Lloop1           (*)  Loop while RCX != 0            (*)    .Lstore_result:        mov     %rax, F           (*)  Store result in F              (*)    end ['rax', 'rcx'];           (*)  Tell compiler register change  (*)    Result := F;END;var    N       : integer = 20 ;begin    writeln;    writeln( BasicFact(N));end.        (*)    Function Fact    (*)

JPD 2021/03/24 Updated: 2025-04-06T17:11:16

Output2432902008176640000

using FreePascal with GMP lib

Works with:Free Pascal version 3.2.0
program GMPfact;{$mode objfpc}uses    gmp    ;    function Factorial(n: qword): string;        var            ResultMPZ: mpz_t;            i: qword;        begin            mpz_init_set_ui(ResultMPZ, 1);            for i := 2 to n do                mpz_mul_ui(ResultMPZ, ResultMPZ, i);            Result := mpz_get_str(nil, 10, ResultMPZ);            mpz_clear(ResultMPZ);        end;var    N     : integer = 101 ;    Fact  :        string ;begin    Fact := Factorial(101);    writeln( N ,'! = ', Fact);end.    (*)     GMPfact     (*)Output:101! = 9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000

JPD 2021/05/15 Updated: 2025-04-06T14:14:33

Recursive

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

PascalABC.NET

function FactIter(n: integer): BigInteger;begin  Result := 1;  for var i:=2 to n do    Result *= i;end;function FactRec(n: integer): BigInteger;begin  if n = 0 then    Result := 1  else Result := n * FactRec(n - 1);end;begin  for var i:=1 to 20 do    Println(i,FactRec(i),FactIter(i));end.
Output:
8 40320 403209 362880 36288010 3628800 362880011 39916800 3991680012 479001600 47900160013 6227020800 622702080014 87178291200 8717829120015 1307674368000 130767436800016 20922789888000 2092278988800017 355687428096000 35568742809600018 6402373705728000 640237370572800019 121645100408832000 12164510040883200020 2432902008176640000 2432902008176640000

Pebble

;Factorial example program for x86 DOS;Compiles to 207 bytes com executableprogram examples\fctrldataint f[1]int n[0]beginecho "Factorial"echo "Enter an integer: "input [n]label loop[f] = [f] * [n]-1 [n]if [n] > 0 then loopecho [f]pausekillend

Peloton

Peloton has an opcode for factorial so there's not much point coding one.

<@ SAYFCTLIT>5</@>

However, just to prove that it can be done, here's one possible implementation:

<@ DEFUDOLITLIT>FAT|__Transformer|<@ LETSCPLIT>result|1</@><@ ITEFORPARLIT>1|<@ ACTMULSCPPOSFOR>result|...</@></@><@ LETRESSCP>...|result</@></@><@ SAYFATLIT>123</@>

Perl

Iterative

sub factorial{  my $n = shift;  my $result = 1;  for (my $i = 1; $i <= $n; ++$i)  {    $result *= $i;  };  $result;}# using a .. rangesub factorial {    my $r = 1;    $r *= $_ for 1..shift;    $r;}

Recursive

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

Functional

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

Modules

Each of these will print 35660, the number of digits in 10,000!.

Library:ntheory
use ntheory qw/factorial/;# factorial returns a UV (native unsigned int) or Math::BigInt depending on sizesay length(  factorial(10000)  );
use bigint;say length(  10000->bfac  );
use Math::GMP;say length(  Math::GMP->new(10000)->bfac  );
use Math::Pari qw/ifact/;say length(  ifact(10000)  );

Peylang

-- calculate factorialchiz a = 5;chiz n = 1;ta a >= 2{    n *= a;    a -= 1;}chaap n;

Phix

Library:Phix/basics

standard iterative factorial builtin, reproduced below. returns inf for 171 and above, and is not accurate above 22 on 32-bit, or 25 on 64-bit.

globalfunctionfactorial(integern)atomres=1whilen>1dores*=nn-=1endwhilereturnresendfunction

The compiler knows where to find that for you, so a runnable program is just

?factorial(8)
Output:
40320

gmp

Library:Phix/mpfr

For seriously big numbers, with perfect accuracy, use the mpz_fac_ui() routine. For a bit of fun, we'll see just how far we can push it, in ten seconds or less.

withjavascript_semanticsincludempfr.empzf=mpz_init()integern=2boolstill_running=true,still_printing=trueconstantten_s=iff(platform()=JS?0.2:10)-- (10s on desktop/Phix, 0.2s under p2js)whilestill_runningdoatomt0=time()mpz_fac_ui(f,n)still_running=(time()-t0)<ten_s-- (stop once over 10s)stringct=elapsed(time()-t0),res,what,ptt0=time()ifstill_printingthenres=shorten(mpz_get_str(f))what="printed"still_printing=(time()-t0)<ten_s-- (stop once over 10s)elseres=sprintf("%,d digits",mpz_sizeinbase(f,10))what="size in base"endifpt=elapsed(time()-t0)printf(1,"factorial(%d):%s, calculated in %s, %s in %s\n",{n,res,ct,what,pt})n*=2endwhile
Output:
factorial(2):2, calculated in 0.0s, printed in 0.0sfactorial(4):24, calculated in 0s, printed in 0sfactorial(8):40320, calculated in 0s, printed in 0sfactorial(16):20922789888000, calculated in 0s, printed in 0sfactorial(32):263130836933693530167218012160000000, calculated in 0s, printed in 0sfactorial(64):1268869321858841641...4230400000000000000 (90 digits), calculated in 0s, printed in 0sfactorial(128):3856204823625804217...0000000000000000000 (216 digits), calculated in 0s, printed in 0sfactorial(256):8578177753428426541...0000000000000000000 (507 digits), calculated in 0s, printed in 0sfactorial(512):3477289793132605363...0000000000000000000 (1,167 digits), calculated in 0s, printed in 0sfactorial(1024):5418528796058857283...0000000000000000000 (2,640 digits), calculated in 0s, printed in 0sfactorial(2048):1672691931910011705...0000000000000000000 (5,895 digits), calculated in 0s, printed in 0sfactorial(4096):3642736389457041931...0000000000000000000 (13,020 digits), calculated in 0s, printed in 0sfactorial(8192):1275885799409419815...0000000000000000000 (28,504 digits), calculated in 0s, printed in 0sfactorial(16384):1207246711959629373...0000000000000000000 (61,937 digits), calculated in 0s, printed in 0.0sfactorial(32768):9092886296374209477...0000000000000000000 (133,734 digits), calculated in 0s, printed in 0.1sfactorial(65536):5162948523097509165...0000000000000000000 (287,194 digits), calculated in 0.0s, printed in 0.2sfactorial(131072):2358150556532892503...0000000000000000000 (613,842 digits), calculated in 0.0s, printed in 0.8sfactorial(262144):1396355768630047926...0000000000000000000 (1,306,594 digits), calculated in 0.1s, printed in 3.1sfactorial(524288):5578452507102649524...0000000000000000000 (2,771,010 digits), calculated in 0.3s, printed in 13.4sfactorial(1048576):5,857,670 digits, calculated in 0.7s, size in base in 0.2sfactorial(2097152):12,346,641 digits, calculated in 1.7s, size in base in 0.5sfactorial(4194304):25,955,890 digits, calculated in 3.6s, size in base in 1.0sfactorial(8388608):54,436,999 digits, calculated in 8.1s, size in base in 2.2sfactorial(16777216):113,924,438 digits, calculated in 17.7s, size in base in 4.9s

Phixmonti

/# recursive #/def factorial    dup 1 > if        dup 1 - factorial *    else        drop 1    endifenddef/# iterative #/def factorial2    1 swap for * endforenddef0 22 2 tolist for    "Factorial(" print dup print ") = " print factorial2 print nlendfor

PHP

Iterative

<?phpfunction factorial($n) {  if ($n < 0) {    return 0;  }  $factorial = 1;  for ($i = $n; $i >= 1; $i--) {    $factorial = $factorial * $i;  }  return $factorial;}?>

Recursive

<?phpfunction factorial($n) {  if ($n < 0) {    return 0;  }  if ($n == 0) {    return 1;  }  else {    return $n * factorial($n-1);  }}?>

One-Liner

<?phpfunction factorial($n) { return $n == 0 ? 1 : array_product(range(1, $n)); }?>

Library

Requires the GMP library to be compiled in:

gmp_fact($n)

Picat

fact(N) = prod(1..N)

Note: Picat hasfactorial/1 as a built-in function.

PicoLisp

(de fact (N)   (if (=0 N)      1      (* N (fact (dec N))) ) )

or:

(de fact (N)   (apply * (range 1 N) ) )

which only works for 1 and bigger.

Piet

Codel width: 25

This is the text code. It is a bit difficult to write as there are some loops and loops doesn't really show well when I write it down as there is no way to explicitly write a loop in the language. I have tried to comment as best to show how it works

push 1notin(number)duplicate not        // label apointer    // pointer 1duplicatepush 1subtractpush 1pointerpush 1nooppointerduplicate  // the next op is back at label apush 1     // this part continues from pointer 1nooppush 2     // label bpush 1rot 1 2duplicatenotpointer    // pointer 2multiplypush 3pointerpush 3pointerpush 3push 3pointerpointer    // back at label bpop        // continues from pointer 2out(number)exit

Plain English

Due to the compiler being implemented in 32-bit, this implementation can calculate only up to 12!.

A factorial is a number.To run:  Start up.  Demonstrate input.  Write "Bye-bye!" to the console.  Wait for 1 second.  Shut down. To demonstrate input:  Write "Enter a number: " to the console without advancing.  Read a string from the console.  If the string is empty, exit.  Convert the string to a number.  If the number is negative, repeat.  Compute a factorial of the number.  Write "Factorial of the number: " then the factorial then the return byte to the console.  Repeat.To decide if a string is empty:  If the string's length is 0, say yes.  Say no.To compute a factorial of a number:  If the number is 0, put 1 into the factorial; exit.  Compute another factorial of the number minus 1.  \ recursion  Put the other factorial times the number into the factorial.

PL/0

The program waits forn. Then it displaysn!.

var n, f;begin  ? n;  f := 1;  while n <> 0 do  begin    f := f * n;    n := n - 1  end;  ! fend.

2 runs.

Input:
5
Output:
     120
Input:
7
Output:
    5040

PL/I

factorial: procedure (N) returns (fixed decimal (30));   declare N fixed binary nonassignable;   declare i fixed decimal (10);   declare F fixed decimal (30);   if N < 0 then signal error;   F = 1;   do i = 2 to N;      F = F * i;   end;   return (F);end factorial;

PL/SQL

Declare  /*====================================================================================================  -- For     :  https://rosettacode.org/  -- --  -- Task    : Factorial  -- Method  : iterative  -- Language: PL/SQL  --  -- 2020-12-30 by alvalongo  ====================================================================================================*/  --  function fnuFactorial(inuValue   integer)  return number  is    nuFactorial number;  Begin    if inuValue is not null then       nuFactorial:=1;       --       if inuValue>=1 then          --          For nuI in 1..inuValue loop              nuFactorial:=nuFactorial*nuI;          end loop;          --       End if;       --    End if;    --    return(nuFactorial);  End fnuFactorial;BEGIN  For nuJ in 0..100 loop      Dbms_Output.Put_Line('Factorial('||nuJ||')='||fnuFactorial(nuJ));  End loop;END;
Output:
TextPL/SQL block, executed in 115 msFactorial(0)=1Factorial(1)=1Factorial(2)=2Factorial(3)=6Factorial(4)=24Factorial(5)=120Factorial(6)=720Factorial(7)=5040Factorial(8)=40320Factorial(9)=362880Factorial(10)=3628800Factorial(11)=39916800Factorial(12)=479001600Factorial(13)=6227020800Factorial(14)=87178291200Factorial(15)=1307674368000Factorial(16)=20922789888000Factorial(17)=355687428096000Factorial(18)=6402373705728000Factorial(19)=121645100408832000Factorial(20)=2432902008176640000Factorial(21)=51090942171709440000Factorial(22)=1124000727777607680000Factorial(23)=25852016738884976640000Factorial(24)=620448401733239439360000Factorial(25)=15511210043330985984000000Factorial(26)=403291461126605635584000000Factorial(27)=10888869450418352160768000000Factorial(28)=304888344611713860501504000000Factorial(29)=8841761993739701954543616000000Factorial(30)=265252859812191058636308480000000Factorial(31)=8222838654177922817725562880000000Factorial(32)=263130836933693530167218012160000000Factorial(33)=8683317618811886495518194401280000000Factorial(34)=295232799039604140847618609643520000000Factorial(35)=10333147966386144929666651337523200000000Factorial(36)=371993326789901217467999448150835200000000Factorial(37)=13763753091226345046315979581580902400000000Factorial(38)=523022617466601111760007224100074291200000000Factorial(39)=20397882081197443358640281739902897356800000000Factorial(40)=815915283247897734345611269596115894272000000000Factorial(41)=33452526613163807108170062053440751665150000000000Factorial(42)=1405006117752879898543142606244511569936000000000000Factorial(43)=60415263063373835637355132068513997507200000000000000Factorial(44)=2658271574788448768043625811014615890320000000000000000Factorial(45)=119622220865480194561963161495657715064000000000000000000Factorial(46)=5502622159812088949850305428800254892944000000000000000000Factorial(47)=258623241511168180642964355153611979968400000000000000000000Factorial(48)=12413915592536072670862289047373375038480000000000000000000000Factorial(49)=608281864034267560872252163321295376886000000000000000000000000Factorial(50)=30414093201713378043612608166064768844300000000000000000000000000Factorial(51)=1551118753287382280224243016469303211060000000000000000000000000000Factorial(52)=80658175170943878571660636856403766975120000000000000000000000000000Factorial(53)=4274883284060025564298013753389399649681000000000000000000000000000000Factorial(54)=230843697339241380472092742683027581082800000000000000000000000000000000Factorial(55)=12696403353658275925965100847566516959550000000000000000000000000000000000Factorial(56)=710998587804863451854045647463724949735000000000000000000000000000000000000Factorial(57)=40526919504877216755680601905432322134900000000000000000000000000000000000000Factorial(58)=2350561331282878571829474910515074683820000000000000000000000000000000000000000Factorial(59)=138683118545689835737939019720389406345000000000000000000000000000000000000000000Factorial(60)=8320987112741390144276341183223364380700000000000000000000000000000000000000000000Factorial(61)=507580213877224798800856812176625227222700000000000000000000000000000000000000000000Factorial(62)=31469973260387937525653122354950764087810000000000000000000000000000000000000000000000Factorial(63)=1982608315404440064116146708361898137532000000000000000000000000000000000000000000000000Factorial(64)=126886932185884164103433389335161480802000000000000000000000000000000000000000000000000000Factorial(65)=8247650592082470666723170306785496252130000000000000000000000000000000000000000000000000000Factorial(66)=544344939077443064003729240247842752641000000000000000000000000000000000000000000000000000000Factorial(67)=36471110918188685288249859096605464426900000000000000000000000000000000000000000000000000000000Factorial(68)=2480035542436830599600990418569171581030000000000000000000000000000000000000000000000000000000000Factorial(69)=171122452428141311372468338881272839091000000000000000000000000000000000000000000000000000000000000Factorial(70)=1,197857166996989179607278372168909873640000000000000000000000000000000000000000000000000000000E+100Factorial(71)=8,504785885678623175211676442399260102844000000000000000000000000000000000000000000000000000000E+101Factorial(72)=6,123445837688608686152407038527467274048000000000000000000000000000000000000000000000000000000E+103Factorial(73)=4,470115461512684340891257138125051110055000000000000000000000000000000000000000000000000000000E+105Factorial(74)=3,307885441519386412259530282212537821441000000000000000000000000000000000000000000000000000000E+107Factorial(75)=2,480914081139539809194647711659403366081000000000000000000000000000000000000000000000000000000E+109Factorial(76)=1,885494701666050254987932260861146558222000000000000000000000000000000000000000000000000000000E+111Factorial(77)=1,451830920282858696340707840863082849831000000000000000000000000000000000000000000000000000000E+113Factorial(78)=1,132428117820629783145752115873204622868000000000000000000000000000000000000000000000000000000E+115Factorial(79)=8,946182130782975286851441715398316520660000000000000000000000000000000000000000000000000000000E+116Factorial(80)=7,156945704626380229481153372318653216530000000000000000000000000000000000000000000000000000000E+118Factorial(81)=5,797126020747367985879734231578109105390000000000000000000000000000000000000000000000000000000E+120Factorial(82)=4,753643337012841748421382069894049466420000000000000000000000000000000000000000000000000000000E+122Factorial(83)=3,945523969720658651189747118012061057130000000000000000000000000000000000000000000000000000000E+124Factorial(84)=~Factorial(85)=~Factorial(86)=~Factorial(87)=~Factorial(88)=~Factorial(89)=~Factorial(90)=~Factorial(91)=~Factorial(92)=~Factorial(93)=~Factorial(94)=~Factorial(95)=~Factorial(96)=~Factorial(97)=~Factorial(98)=~Factorial(99)=~Factorial(100)=~Total execution time 176 ms

Pluto

Translation of:Wren
local bigint = require "pluto:bigint"class Factorial    static function iterative(n)        local fact = bigint.new(1)        if n < 2 then return fact end        for i = 2, n do fact *= bigint.new(i) end        return fact    end    static function recursive(n)        if n < 2 then return bigint.new(1) end        return bigint.new(n) * Factorial.recursive(n - 1)    endendlocal function commatize(n)    local s = n:tostring()    local zero = bigint.new(0)    if n < zero then s = s:sub(2) end    for i = #s - 3, 1, -3 do        s = s:sub(1, i) .. "," .. s:sub(i + 1)    end    if n >= zero then return s end    return "-" .. sendlocal n = 24print($"Factorial({n}) iterative -> {commatize(Factorial.iterative(n))}")print($"Factorial({n}) recursive -> {commatize(Factorial.recursive(n))}")
Output:
Factorial(24) iterative -> 620,448,401,733,239,439,360,000Factorial(24) recursive -> 620,448,401,733,239,439,360,000

PostScript

Recursive

/fact {  dup 0 eq     % check for the argument being 0  {    pop 1      % if so, the result is 1  }  {    dup    1 sub    fact       % call recursively with n - 1    mul        % multiply the result with n  } ifelse} def

Iterative

/fact {  1            % initial value for the product  1 1          % for's start value and increment  4 -1 roll    % bring the argument to the top as for's end value  { mul } for} def

Combinator

Library:initlib
/myfact {{dup 0 eq} {pop 1} {dup pred} {mul} linrec}.

PowerShell

Recursive

function Get-Factorial ($x) {    if ($x -eq 0) {        return 1    }    return $x * (Get-Factorial ($x - 1))}

Iterative

function Get-Factorial ($x) {    if ($x -eq 0) {        return 1    } else {        $product = 1        1..$x | ForEach-Object { $product *= $_ }        return $product    }}

Evaluative

Works with:PowerShell version 2

This one first builds a string, containing1*2*3... and then lets PowerShell evaluate it. A bit of mis-use but works.

function Get-Factorial ($x) {    if ($x -eq 0) {        return 1    }    return (Invoke-Expression (1..$x -join '*'))}

Processing

Recursive

int fact(int n){if(n <= 1){return 1;} else{return n*fact(n-1);}}
Output:
returns the appropriate value as an int

Iterative

long fi(int n) {    if (n < 0){      return -1;    }        if (n == 0){      return 1;    } else {      long r = 1;            for (long i = 1; i <= n; i++){        r = r * i;      }            return r;    }}
Output:
for n < 0 the function returns -1 as an error code. for n >= 0 the appropriate value is returned as a long.

Prolog

Works with:SWI Prolog

Recursive

fact(X, 1) :- X<2.fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*X.

Tail recursive

fact(N, NF) :-fact(1, N, 1, NF).fact(X, X, F, F) :- !.fact(X, N, FX, F) :-X1 is X + 1,FX1 is FX * X1,fact(X1, N, FX1, F).

Fold

We can simulate foldl.

% foldl(Pred, Init, List, R).%foldl(_Pred, Val, [], Val).foldl(Pred, Val, [H | T], Res) :-call(Pred, Val, H, Val1),foldl(Pred, Val1, T, Res).% factorialp(X, Y, Z) :- Z is X * Y).fact(X, F) :-numlist(2, X, L),foldl(p, 1, L, F).

Fold with anonymous function

Using the module lambda written by Ulrich Neumerkel found therehttp://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl, we can use anonymous functions and write :

:- use_module(lambda).% foldl(Pred, Init, List, R).%foldl(_Pred, Val, [], Val).foldl(Pred, Val, [H | T], Res) :-call(Pred, Val, H, Val1),foldl(Pred, Val1, T, Res).fact(N, F) :-numlist(2, N, L),foldl(\X^Y^Z^(Z is X * Y), 1, L, F).

Continuation passing style

Works with SWI-Prolog and module lambda written byUlrich Neumerkel found therehttp://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl.

:- use_module(lambda).fact(N, FN) :-cont_fact(N, FN, \X^Y^(Y = X)).cont_fact(N, F, Pred) :-(   N = 0 ->    call(Pred, 1, F);   N1 is N - 1,    P =  \Z^T^(T is Z * N),    cont_fact(N1, FT, P),    call(Pred, FT, F)).

Pure

Recursive

fact n = n*fact (n-1) if n>0;       = 1 otherwise;let facts = map fact (1..10); facts;

Tail Recursive

fact n = loop 1 n with  loop p n = if n>0 then loop (p*n) (n-1) else p;end;

Python

Library

Works with:Python version 2.6+, 3.x
import mathmath.factorial(n)

Iterative

def factorial(n):    result = 1    for i in range(1, n+1):        result *= i    return result

Functional

from operator import mulfrom functools import reducedef factorial(n):    return reduce(mul, range(1,n+1), 1)

or

from itertools import (accumulate, chain)from operator import mul# factorial :: Integerdef factorial(n):    return list(        accumulate(chain([1], range(1, 1 + n)), mul)    )[-1]

or including the sequence that got us there:

from itertools import (accumulate, chain)from operator import mul# factorials :: [Integer]def factorials(n):    return list(        accumulate(chain([1], range(1, 1 + n)), mul)    )print(factorials(5))# -> [1, 1, 2, 6, 24, 120]

or

from numpy import proddef factorial(n):    return prod(range(1, n + 1), dtype=int)

Recursive

def factorial(n):    z=1    if n>1:        z=n*factorial(n-1)    return z
Output:
>>> for i in range(6):    print(i, factorial(i))   0 11 12 23 64 245 120>>>

or

def factorial(n):    return n * factorial(n - 1) if n else 1

Numerical Approximation

The following sample uses Lanczos approximation fromwp:Lanczos_approximation to approximate the gamma function.

The gamma function Γ(x) extends the domain of the factorial function, while maintaining the relationship that factorial(x) = Γ(x+1).

from cmath import *# Coefficients used by the GNU Scientific Libraryg = 7p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,     771.32342877765313, -176.61502916214059, 12.507343278686905,     -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]def gamma(z):  z = complex(z)  # Reflection formula  if z.real < 0.5:    return pi / (sin(pi*z)*gamma(1-z))  else:    z -= 1    x = p[0]    for i in range(1, g+2):      x += p[i]/(z+i)    t = z + g + 0.5    return sqrt(2*pi) * t**(z+0.5) * exp(-t) * xdef factorial(n):  return gamma(n+1)print "factorial(-0.5)**2=",factorial(-0.5)**2for i in range(10):  print "factorial(%d)=%s"%(i,factorial(i))
Output:
factorial(-0.5)**2= (3.14159265359+0j)factorial(0)=(1+0j)factorial(1)=(1+0j)factorial(2)=(2+0j)factorial(3)=(6+0j)factorial(4)=(24+0j)factorial(5)=(120+0j)factorial(6)=(720+0j)factorial(7)=(5040+0j)factorial(8)=(40320+0j)factorial(9)=(362880+0j)

Q

Iterative

Point-free

f:(*/)1+til@

or

f:(*)over 1+til@

or

f:prd 1+til@

As a function

f:{(*/)1+til x}

Recursive

f:{$[x=1;1;x*.z.s x-1]}

Quackery

Iterative

  [ 1 swap times [ i 1+ * ] ] is ! ( n --> n! )

Overly Complicated and Inefficient

Words named in the form [Annnnnn] refer to entries in the The On-Line Encyclopedia of Integer Sequences®[1].

  [ 1 & ]                   is odd       ( n --> b )  [ odd not ]               is even      ( n --> b )  [ 1 >> ]                  is 2/        ( n --> n )  [ [] swap       witheach       [ i^ swap - join ] ]  is [i^-]     ( [ --> [ ) [ 1 split    witheach       [ over -1 peek         * join ] ]          is [prod]    ( [ --> [ )  [ 1 -  ' [ 0 ]    swap times      [ dup i^ 1+        dup dip           [ 2/ peek ]         odd +        join ] ]            is [A000120] ( n --> [ )  [ [A000120] [i^-] ]       is [A011371] ( n --> [ )  [ ' [ 0 ] swap    1 - times      [ i^ 1+ dup even if        [ dip dup 2/ peek ]        join ]     behead drop ]           is [A000265] ( n --> [ ) [ ' [ 1 ] swap dup    [A000265] [prod]   swap [A011371]   swap  witheach      [ over i^ 1+ peek       << rot swap join        swap ] drop ]        is [A000142] ( n --> [ )[ 1+ [A000142] -1 peek ]    is !

R

Recursive

fact <- function(n) {  if (n <= 1) 1  else n * Recall(n - 1)}

Iterative

factIter <- function(n) {  f = 1  if (n > 1) {    for (i in 2:n) f <- f * i  }  f}

Numerical Approximation

R has a native gamma function and a wrapper for that function that can produce factorials. E.g.

print(factorial(50)) # 3.041409e+64

Functional

 fact_fp <- function(n) ifelse(!n, 1, Reduce(`*`, seq_len(n)))

Racket

Recursive

The standard recursive style:

(define (factorial n)  (if (= 0 n)      1      (* n (factorial (- n 1)))))

However, it is inefficient. It's more efficient to use an accumulator.

(define (factorial n)  (define (fact n acc)    (if (= 0 n)         acc        (fact (- n 1) (* n acc))))  (fact n 1))

Fold

We can also define factorial as for/fold (product startvalue) (range) (operation))

(define (factorial n)  (for/fold ([pro 1]) ([i (in-range 1 (+ n 1))]) (* pro i)))

Or quite simpler by an for/product

(define (factorial n)  (for/product ([i (in-range 1 (+ n 1))]) i))

Raku

(formerly Perl 6)

via User-defined Postfix Operator

[*] is a reduction operator that multiplies all the following values together. Note that we don't need to start at 1, since the degenerate case of[*]() correctly returns 1, and multiplying by 1 to start off with is silly in any case.

Works with:Rakudo version 2015.12
sub postfix:<!> (Int $n) { [*] 2..$n }say 5!;
Output:
120

via Memoized Constant Sequence

This approach is much more efficient for repeated use, since it automatically caches.[\*] is the so-called triangular version of [*]. It returns the intermediate results as a list. Note that Raku allows you to define constants lazily, which is rather helpful when your constant is of infinite size...

Works with:Rakudo version 2015.12
constant fact = 1, |[\*] 1..*;say fact[5]
Output:
120

Rapira

Iterative

Фун Факт(n)  f := 1  для i от 1 до n        f := f * i  кц  Возврат fКон Фун

Recursive

Фун Факт(n)  Если n = 1    Возврат 1  Иначе    Возврат n * Факт(n - 1)  ВсёКон ФунПроц Старт()  n := ВводЦел('Введите число (n <= 12) :')  печать 'n! = '  печать Факт(n)Кон проц

Recursive (English)

fun factorial(number)  if number = 0 then    return 1  fi  return number * factorial(number - 1)end

Rascal

Iterative

The standard implementation:

public int factorial_iter(int n){result = 1;for(i <- [1..n])result *= i;return result;}

However, Rascal supports an even neater solution. By using areducer we can write this code on one short line:

public int factorial_iter2(int n) = (1 | it*e | int e <- [1..n]);
Output:
rascal>factorial_iter(10)int: 3628800rascal>factorial_iter2(10)int: 3628800

Recursive

public int factorial_rec(int n){if(n>1) return n*factorial_rec(n-1);else return 1;}
Output:
rascal>factorial_rec(10)int: 3628800

RASEL

1&$:?v:1-3\$/1\     >$11\/.@

Rebol

Rebol [    Title: "Factorial"    URL: http://rosettacode.org/wiki/Factorial_function] ;; Standard recursive implementation.factorial: func [n][    either n > 1 [n * factorial n - 1] [1]] ;; Iteration.ifactorial: func [n][    f: 1    for i 2 n 1 [f: f * i]    f]either system/version < 3.0.0 [    ; Automatic memoization.    ; I'm just going to say up front that this is a stunt. However, you've    ; got to admit it's pretty nifty. Note that the 'memo' function    ; works with an unlimited number of arguments (although the expected    ; gains decrease as the argument count increases).    memo: func [        "Defines memoizing function -- keeps arguments/results for later use."        args [block!] "Function arguments. Just specify variable names."        body [block!] "The body block of the function."        /local m-args m-r    ][        do compose/deep [            func [                (args)                /dump "Dump memory."            ][                m-args: []                if dump [return m-args]                                if m-r: select/only m-args reduce [(args)] [return m-r]                                m-r: do [(body)]                append m-args reduce [reduce [(args)] m-r]                m-r            ]        ]    ]    mfactorial: memo [n][        either n > 1 [n * mfactorial n - 1] [1]    ]][    ;; Above hack is not supported in Rebol3    mfactorial: func[i][none]] ;; Test them on numbers zero to ten.for i 0 10 1 [print [i ":" factorial i  ifactorial i  mfactorial i]]
Output:
0 : 1 1 11 : 1 1 12 : 2 2 23 : 6 6 64 : 24 24 245 : 120 120 1206 : 720 720 7207 : 5040 5040 50408 : 40320 40320 403209 : 362880 362880 36288010 : 3628800 3628800 3628800

Red

Iterative (variants):

fac: function [n][r: 1 repeat i n [r: r * i] r]fac: function [n][repeat i also n n: 1 [n: n * i] n]

Recursive (variants):

fac: func [n][either n > 1 [n * fac n - 1][1]]fac: func [n][any [if n = 0 [1] n * fac n - 1]]fac: func [n][do pick [[n * fac n - 1] 1] n > 1]

Memoized:

fac: function [n][m: #(0 1) any [m/:n m/:n: n * fac n - 1]]

Refal

$ENTRY Go {    = <Facts 0 10>;}Facts {    s.N s.Max, <Compare s.N s.Max>: '+' = ;    s.N s.Max = <Prout <Symb s.N>'! = ' <Fact s.N>>                <Facts <+ s.N 1> s.Max>;};Fact {    0   = 1;    s.N = <* s.N <Fact <- s.N 1>>>;};
Output:
0! = 11! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 3628800

Relation

function factorial (n)set result = 1if n > 1set k = 2while k <= nset result = result * kset k = k + 1end whileend ifend function

Retro

A recursive implementation from the benchmarking code.

:<factorial>  dup #1 -eq? 0; drop  dup n:dec <factorial> * ;:factorial  dup n:zero?  [ n:inc ]  [ <factorial> ] choose ;

REXX

Modules:How to use
Modules:Source code

Both Regina and ooRexx can handle numbers up to a magnitude (exponent) of 1 billion and up to a precision (digits) of 1 billion, as I will show below.

This code snippet

call time('r')numeric digits 999999999a = 10/3say length(a) time('e')

runs under Regina and ooRexx, producing correct output in about 15 seconds! But single variable 'a' consumes 2.9GB memory in Regina and 6.6GB in ooRexx...

The factorial function is typically used as subroutine in other programs. Then it has a given precision, and there's no use in extending the numeric digits or other tricks. Of course a bigger n! will switch to floating point and loose accuracy in the last few digits. That all is the responsibility of the calling program.

Now, run below program. Procedure Fact in module Special uses the standard repeated multiplication and memoization in case of multiple calls with the same parameter. No attempt was made to implement one of the faster algorithms, like the binary tree multiplication method.

-- 23 Aug 2025include Settingsay 'Factorial'say versionsaycall First20call Imperative 10, '1 13 71 450 3249 25206 205022 1723508 14842907 130202808'if pos('Regina',version) > 0 then   call Recursive 10, '1 13 71 450 3249 25206 205022'else   call Recursive 10, '1 13 71 450 3249'call Imperative 1E5,'1 13 71 450 3249 25206'call TimerexitFirst20:say 'First 20 FactorialS...'numeric digits 30do n = 1 to 20   say n'! =' Fact(n)endsayreturnImperative:call ResetMemocall Time('R')arg d,pnumeric digits d; Fact. = 0say 'Imperative in' d 'digits precision...'do i = 1 to Words(p)   call Time('r'); f = Word(p,i); h = Fact(f)   parse var h 'E' e   if e = '' then      say Right(f'!',10) 'has exact' Right(Length(h),9) 'digits' '('Format(Time('e'),,3)'s)'   else      say Right(f'!',10) 'has about' Right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)'endsayreturnRecursive:call ResetMemocall Time('R')arg d,pnumeric digits d; Fact. = 0say 'Recursive in' d 'digits precision...'do i = 1 to Words(p)   call Time('r'); f = Word(p,i); h = Recurs(f)   parse var h 'E' e   if e = '' then      say Right(f'!',10) 'has exact' Right(Length(h),9)  'digits' '('Format(Time('e'),,3)'s)'   else      say Right(f'!',10) 'has about' Right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)'endsayreturnRecurs:procedurearg xxif xx = 0 then   return 1else   return xx*Recurs(xx-1)include Math
Output:
FACTORIALREXX-Regina_3.9.7(MT) 5.00 18 Mar 2025First 20 factorials...1! = 12! = 23! = 64! = 245! = 1206! = 7207! = 50408! = 403209! = 36288010! = 362880011! = 3991680012! = 47900160013! = 622702080014! = 8717829120015! = 130767436800016! = 2092278988800017! = 35568742809600018! = 640237370572800019! = 12164510040883200020! = 2432902008176640000Imperative in 10 digits precision...        1! has exact         1 digits (0.000s)       13! has exact        10 digits (0.000s)       71! has about       102 digits (0.000s)      450! has about      1001 digits (0.000s)     3249! has about     10001 digits (0.001s)    25206! has about    100001 digits (0.011s)   205022! has about   1000000 digits (0.099s)  1723508! has about  10000002 digits (0.924s) 14842907! has about 100000001 digits (9.342s)130202808! has about 999999999 digits (86.826s)Recursive in 10 digits precision...        1! has exact         1 digits (0.000s)       13! has exact        10 digits (0.000s)       71! has about       102 digits (0.000s)      450! has about      1001 digits (0.001s)     3249! has about     10001 digits (0.008s)    25206! has about    100001 digits (0.063s)   205022! has about   1000000 digits (0.626s)Imperative in 1E6 digits precision...        1! has exact         1 digits (0.000s)       13! has exact        10 digits (0.004s)       71! has exact       102 digits (0.023s)      450! has exact      1001 digits (0.159s)     3249! has exact     10001 digits (1.397s)    25206! has exact    100001 digits (38.039s)

You see (from 130202808!) that REXX can calculate up to very high magnitudes. And 205022! estimated in 10 digits takes 0.626s and exact in 1E6 digits takes 38.039. Conclusion: yes, you might calculate say 1e6! in say 6 million digits, but in practice it will take hours.

Rhombus

Recursive

#lang rhombus/staticfun factorial:| factorial(0): 1| factorial(n): n * factorial(n - 1)

Iterative

#lang rhombus/staticfun factorial(n):  for values(a=1) (n in 1..=n):    a * nfactorial(6) // output: 720

Rhovas

Solutions support arbitrarily large numbers as Rhovas'sInteger type is arbitrary-precision (JavaBigInteger). Additional notes:

Iterative

Standard iterative solution using afor loop:

func factorial(num: Integer): Integer {    require num >= 0;    var result = 1;    for (val i in range(2, num, :incl)) {        result = result * i;    }    return result;}

Recursive

Standard recursive solution using a pattern matching approach:

func factorial(num: Integer): Integer {    require num >= 0;    match {        num == 0: return 1;        else: return num * factorial(num - 1);    }}

Ring

give nx = fact(n)see n + " factorial is : " + xfunc fact nr if nr = 1 return 1 else return nr * fact(nr-1) ok

Robotic

Iterative

input string "Enter a number:"set "in" to "('ABS('input')')"if "in" <= 1 then "one"set "result" to 1: "factorial"set "result" to "('result' * 'in')"dec "in" by 1if "in" > 1 then "factorial"* "('result')"end: "one"* "1"end

Rockstar

Here's the "minimized" Rockstar:

Factorial takes a numberIf a number is 0Give back 1.Put a number into the firstKnock a number downGive back the first times Factorial taking a number

And here's a more "idiomatic" version:

Real Love takes a heartA page is a memory.Put A page over A page into the bookIf a heart is nothingGive back the bookPut a heart into my handsKnock my hands downGive back a heart of Real Love taking my hands

Rocq

Fixpoint factorial (n : nat) : nat :=  match n with    | 0 => 1    | S k => (S k) * (factorial k)  end.

RPL

We can either directly callFACT or recode it in two ways:

Iterative

IF DUP 2 <THEN DROP 1ELSE     DUPWHILE DUP 1 >REPEAT 1 - SWAP OVER * SWAPEND     DROPEND≫ 'FACTi' STO

Recursive

IF DUP 2 <THEN DROP 1ELSE DUP 1 - FACTr *END≫ 'FACTr' STO
69 FACT69 FACTi69 FACTr
Output:
3:   1.71122452428E+982:   1.71122452428E+981:   1.71122452428E+98

Ruby

Beware of recursion! Iterative solutions are better for large n.

# Recursivedef factorial_recursive(n)  n.zero? ? 1 : n * factorial_recursive(n - 1)end# Tail-recursivedef factorial_tail_recursive(n, prod = 1)  n.zero? ? prod : factorial_tail_recursive(n - 1, prod * n)end# Iterative with Range#eachdef factorial_iterative(n)  (2...n).each { |i| n *= i }  n.zero? ? 1 : nend# Iterative with Range#injectdef factorial_inject(n)  (1..n).inject(1){ |prod, i| prod * i }end# Iterative with Range#reduce, requires Ruby 1.8.7def factorial_reduce(n)  (2..n).reduce(1, :*)endrequire 'benchmark'n = 400m = 10000Benchmark.bm(16) do |b|  b.report('recursive:')       {m.times {factorial_recursive(n)}}  b.report('tail recursive:')  {m.times {factorial_tail_recursive(n)}}  b.report('iterative:')       {m.times {factorial_iterative(n)}}  b.report('inject:')          {m.times {factorial_inject(n)}}  b.report('reduce:')          {m.times {factorial_reduce(n)}}end

The benchmark depends on the Ruby implementation. WithMRI,#factorial_reduce seems slightly faster than others. This might happen because(1..n).reduce(:*) loops through fast C code, and avoids interpreted Ruby code.

Output:
                       user     system      total        realrecursive:         2.350000   0.260000   2.610000 (  2.610410)tail recursive:    2.710000   0.270000   2.980000 (  2.996830)iterative:         2.250000   0.250000   2.500000 (  2.510037)inject:            2.500000   0.130000   2.630000 (  2.641898)reduce:            2.110000   0.230000   2.340000 (  2.338166)

Rust

fn factorial_recursive (n: u64) -> u64 {    match n {        0 => 1,        _ => n * factorial_recursive(n-1)    }}fn factorial_iterative(n: u64) -> u64 {    (1..=n).product()}fn main () {    for i in 1..10 {        println!("{}", factorial_recursive(i))    }    for i in 1..10 {        println!("{}", factorial_iterative(i))    }}

SASL

Copied from SASL manual, page 3

fac 4where fac 0 = 1      fac n = n * fac (n - 1)?

Sather

class MAIN is  -- recursive  fact(a: INTI):INTI is    if a < 1.inti then return 1.inti; end;    return a * fact(a - 1.inti);  end;  -- iterative  fact_iter(a:INTI):INTI is    s ::= 1.inti;    loop s := s * a.downto!(1.inti); end;    return s;  end;  main is    a :INTI := 10.inti;    #OUT + fact(a) + " = " + fact_iter(a) + "\n";  end;end;

S-BASIC

S-BASIC's double-precision real data type supports up to 14 digits,thereby allowing calculation up to 15! without loss of precision

function factorial(n=real.double)=real.double    if n = 0 then n = 1 else n = n * factorial(n-1)end = nvar i=integerprint "Factorial Calculator"print "  n            n!"print "----------------------"for i=1 to 15    print using "##  #,###,###,###,###";i;factorial(i)next iend

An iterative rather than recursive approach works equally well, if thatis your preference.

function factorial(n=real.double)=real.double    var i, f = real.double    f = 1    for i = 1 to n        f = f * i    next iend = f
Output:
Factorial Calculator  n            n!----------------------  1                  1  2                  2  3                  3  4                 24  5                120  6                720  7              5,040  8             40,320  9            362,880 10          3,628,800 11         39,916,800 12        479,001,600 13      6,227,020,800 14     87,178,291,200 15  1,307,674,368,000


Scala

Imperative

An imperative style using a mutable variable:

def factorial(n: Int) = {  var res = 1  for (i <- 1 to n)    res *= i   res}

Recursive

Using naive recursion:

def factorial(n: Int): Int =   if (n < 1) 1   else       n * factorial(n - 1)

Using tail recursion with a helper function:

def factorial(n: Int) = {  @tailrec def fact(x: Int, acc: Int): Int = {    if (x < 2) acc else fact(x - 1, acc * x)  }  fact(n, 1)}

Stdlib .product

Using standard library builtin:

def factorial(n: Int) = (2 to n).product

Folding

Using folding:

def factorial(n: Int) =  (2 to n).foldLeft(1)(_ * _)

Using implicit functions to extend the Int type

Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:

implicit def IntToFac(i : Int) = new {  def ! = (2 to i).foldLeft(BigInt(1))(_ * _)}
Example used in the REPL:
scala> 20!res0: scala.math.BigInt = 2432902008176640000scala> 100!res1: scala.math.BigInt = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Scheme

Recursive

(define (factorial n)  (if (<= n 0)      1      (* n (factorial (- n 1)))))

The following is tail-recursive, so it is effectively iterative:

(define (factorial n)  (let loop ((i 1)             (accum 1))    (if (> i n)        accum        (loop (+ i 1) (* accum i)))))

Iterative

(define (factorial n)  (do ((i 1 (+ i 1))       (accum 1 (* accum i)))      ((> i n) accum)))

Folding

;Using a generator and a function that apply generated values to a function taking two arguments;A generator knows commands 'next? and 'next(define (range a b)(let ((k a))(lambda (msg)(cond((eq? msg 'next?) (<= k b))((eq? msg 'next)(cond((<= k b) (set! k (+ k 1)) (- k 1))(else 'nothing-left)))))));Similar to List.fold_left in OCaml, but uses a generator(define (fold fun a gen)(let aux ((a a))(if (gen 'next?) (aux (fun a (gen 'next))) a)));Now the factorial function(define (factorial n) (fold * 1 (range 1 n)))(factorial 8);40320

Pragmatic

(define (range n)  (let ((lst '()))    (do ((i 1 (+ i 1)))        ((= i (+ n 1)))      (set! lst (cons i lst)))    (reverse lst)))(define (fact n)  (apply * (range n)))

Scilab

Built-in

The factorial function is built-in to Scilab. The built-in function is only accurate forN21{\displaystyle {\displaystyle N\leq 21}} due to the precision limitations of floating point numbers, but if we want to stay in integers,N13{\displaystyle {\displaystyle N\leq 13}} becauseN!>2311{\displaystyle {\displaystyle N!>2^{3}1-1}}.

answer = factorial(N)

Iterative

function f=factoriter(n)    f=1    for i=2:n        f=f*i    endendfunction

Recursive

function f=factorrec(n)    if n==0 then f=1            else f=n*factorrec(n-1)    endendfunction

Numerical approximation

The gamma function,Γ(z)=0tz1etdt{\displaystyle {\displaystyle \Gamma (z)=\int _{0}^{\infty }t^{z-1}e^{-t}\,\mathrm {d} t\!}}, can be used to calculate factorials, forn!=Γ(n+1){\displaystyle {\displaystyle n!=\Gamma (n+1)}}.

function f=factorgamma(n)    f = gamma(n+1)endfunction

Seed7

Seed7 defines the prefix operator! ,which computes a factorial of aninteger.The maximum representable number of an integer is9223372036854775807.This limits the maximum factorial for integers to factorial(20)=2432902008176640000.Because of this limitations factorial is a very bad example to show the performance advantage of an iterative solution.To avoid this limitations the functions below usebigInteger:

Iterative

const func bigInteger: factorial (in bigInteger: n) is func  result    var bigInteger: fact is 1_;  local    var bigInteger: i is 0_;  begin    for i range 1_ to n do      fact *:= i;    end for;  end func;

Original source:[2]

Recursive

const func bigInteger: factorial (in bigInteger: n) is func  result    var bigInteger: fact is 1_;  begin    if n > 1_ then      fact := n * factorial(pred(n));    end if;  end func;

Original source:[3]

Self

Built in:

n factorial

Iterative version:

factorial: n = (|r <- 1| 1 to: n + 1 Do: [|:i| r: r * i]. r)

Recursive version:

factorial: n = (n <= 1 ifTrue: 1 False: [n * (factorial: n predecessor)])

Factorial is product of list of numbers from 1 to n.(Vector indexes start at 0)

factorial: n = (((vector copySize: n) mapBy: [|:e. :i| i + 1]) product)

SequenceL

The simplest description: factorial is the product of the numbers from 1 to n:

factorial(n) := product(1 ... n);

Or, if you wanted to generate a list of all the factorials:

factorials(n)[i] := product(1 ... i) foreach i within 1 ... n;

Or, written recursively:

factorial: int -> int;factorial(n) :=1 when n <= 0elsen * factorial(n-1);

Tail-recursive:

factorial(n) :=factorialHelper(1, n);factorialHelper(acc, n) :=acc when n <= 0elsefactorialHelper(acc * n, n-1);

SETL

$ Recursiveproc fact(n);    if (n < 2) then        return 1;    else        return n * fact(n - 1);    end if;end proc;$ Iterativeproc factorial(n);    v := 1;    for i in {2..n} loop        v *:= i;    end loop;    return v;end proc;

Shen

(define factorial    0 -> 1    X -> (* X (factorial (- X 1))))

Sidef

Recursive:

func factorial_recursive(n) {    n == 0 ? 1 : (n * __FUNC__(n-1))}

 Catamorphism:

func factorial_reduce(n) {    1..n -> reduce({|a,b| a * b }, 1)}

 Iterative:

func factorial_iterative(n) {    var f = 1    {|i| f *= i } << 2..n    return f}

 Built-in:

say 5!

Simula

begin    integer procedure factorial(n);    integer n;    begin        integer fact, i;        fact := 1;        for i := 2 step 1 until n do            fact := fact * i;        factorial := fact    end;    integer f; outtext("factorials:"); outimage;    for f := 0, 1, 2, 6, 9 do begin        outint(f, 2); outint(factorial(f), 8); outimage    endend
Output:
factorials: 0       1 1       1 2       2 6     720 9  362880

Sisal

Solution using a fold:

define mainfunction main(x : integer returns integer)  for a in 1, x    returns      value of product a  end forend function

Simple example using a recursive function:

define mainfunction main(x : integer returns integer)  if x = 0 then    1  else    x * main(x - 1)  end ifend function

Slate

This is already implemented in the core language as:

n@(Integer traits) factorial"The standard recursive definition."[  n isNegative ifTrue: [error: 'Negative inputs to factorial are invalid.'].  n <= 1    ifTrue: [1]    ifFalse: [n * ((n - 1) factorial)]].

Here is another way to implement it:

n@(Integer traits) factorial2[  n isNegative ifTrue: [error: 'Negative inputs to factorial are invalid.'].  (1 upTo: n by: 1) reduce: [|:a :b| a * b]].
Output:
slate[5]> 100 factorial.93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Slope

Slope supports 64 bit floating point numbers and renders ints via conversion from float.There is no "big int" library. As such the largest integer that can be given the belowfactorial procedures is 171, anything larger will produce+Inf.

Using reduce:

(define factorial (lambda (n)  (cond     ((negative? n) (! "Negative inputs to factorial are invalid"))    ((zero? n) 1)    (else (reduce (lambda (num acc) (* num acc)) 1 (range n 1))))))

Using a loop:

(define factorial (lambda (n)  (cond     ((negative? n) (! "Negative inputs to factorial are invalid"))    ((zero? n) 1)    (else      (for ((acc 1 (* acc i))(i 1 (+ i 1))) ((<= i n) acc))))))

Smalltalk

Smalltalk Number class already has afactorial method ¹;
however, let's see how we could implement it by ourselves.

Iterative with fold

Works with:GNU Smalltalk
Works with:Smalltalk
Number extend [  my_factorial [    (self < 2)         ifTrue: [ ^1 ]        ifFalse: [                     ^ (2 to: self) fold: [ :a :b | a * b ]        ]  ]].7 factorial printNl.7 my_factorial printNl.

Recursive

Number extend [  factorial [    self < 0 ifTrue: [ self error: 'factorial is defined for natural numbers' ].    self isZero ifTrue: [ ^1 ].    ^self * ((self - 1) factorial)  ]].

Recursive (functional)

Defining alocal function (aka closure) named 'fac':

|fac|fac := [:n |    n < 0 ifTrue: [ self error: 'fac is defined for natural numbers' ].    n <= 1         ifTrue: [ 1 ]        ifFalse: [ n * (fac value:(n - 1)) ]].fac value:1000.
Works with:Pharo version 1.3-13315
Works with:Smalltalk/X
| fac |fac := [ :n | (1 to: n) inject: 1 into: [ :prod :next | prod * next ] ]. fac value: 10. "3628800"
Works with:Smalltalk/X
fac := [:n | (1 to: n) product].fac value:40 -> 815915283247897734345611269596115894272000000000

Note ¹) the builtin factorial (where builtin means:the already provided method in the class library) typically uses a *much* better algorithm than both the iterative and especially the recursive versions presented here. So it is a bad idea, to not use them as a programmer.

SNOBOL4

Works with:Macro Spitbol
Works with:CSnobol

Note: Snobol4+ overflows after 7! because of signed short int limitation.

Recursive

        define('rfact(n)') :(rfact_end)rfact   rfact = le(n,0) 1 :s(return)        rfact = n * rfact(n - 1) :(return)rfact_end

Tail-recursive

        define('trfact(n,f)') :(trfact_end)trfact  trfact = le(n,0) f :s(return)        trfact = trfact(n - 1, n * f) :(return)trfact_end

Iterative

        define('ifact(n)') :(ifact_end)ifact   ifact = 1if1     ifact = gt(n,0) n * ifact :f(return)        n = n - 1 :(if1)ifact_end

Test and display factorials 0 .. 10

loop    i = le(i,10) i + 1 :f(end)        output = rfact(i) ' ' trfact(i,1) ' ' ifact(i) :(loop)end
Output:
1 1 12 2 26 6 624 24 24120 120 120720 720 7205040 5040 504040320 40320 40320362880 362880 3628803628800 3628800 362880039916800 39916800 39916800

Soda

Recursive

factorial (n : Int) : Int =  if n < 2  then 1  else n * factorial (n - 1)

Tail recursive

_tailrec_fact (n : Int) (accum : Int) : Int =  if n < 2  then accum  else _tailrec_fact (n - 1) (n * accum)factorial (n : Int) : Int =  _tailrec_fact (n) (1)

SparForte

As a structured script.

#!/usr/local/bin/sparpragma annotate( summary, "factorial n" )       @( description, "Write a function to return the factorial of a number." )       @( author, "Ken O. Burtch" );pragma license( unrestricted );pragma restriction( no_external_commands );procedure factorial is  fact_pos : constant integer := numerics.value( $1 );  result : natural;  count  : natural;begin  if fact_pos < 0 then     put_line( standard_error, source_info.source_location & ": number must be >= 0" );     command_line.set_exit_status( 192 );     return;  end if;  if fact_pos = 0 then     ? 0;     return;  end if;  result := natural( fact_pos );  count  := natural( fact_pos - 1 );  for i in reverse 1..count loop      result := @ * i;  end loop;  ? result;end factorial;

Spin

Works with:BST/BSTC
Works with:FastSpin/FlexSpin
Works with:HomeSpun
Works with:OpenSpin
con  _clkmode = xtal1 + pll16x  _clkfreq = 80_000_000 obj  ser : "FullDuplexSerial.spin" pub main | i  ser.start(31, 30, 0, 115200)  repeat i from 0 to 10    ser.dec(fac(i))    ser.tx(32)  waitcnt(_clkfreq + cnt)  ser.stop  cogstop(0)pub fac(n) : f   f := 1  repeat while n > 0    f *= n    n -= 1
Output:
1 1 2 6 24 120 720 5040 40320 362880 3628800

SPL

fact(n)=  ? n!>1, <=1  <= n*fact(n-1).

SQL

The input number is given in the WHERE clause.

WITH RECURSIVE f(a, b) AS (  VALUES(1, 1)  UNION ALL  SELECT a * b, b + 1 FROM f WHERE b <= 9)SELECT MAX(a) FROM f

SSEM

The factorial function gets large quickly: so quickly that 13! already overflows a 32-bit integer. For any real-world algorithm that may require factorials, therefore, the most economical approach on a machine comparable to the SSEM would be to store the values of 0! to 12! and simply look up the one we want. This program does that. (Note that what we actually store is the two's complement of each value: this is purely because the SSEM cannot load a number from storage without negating it, so providing the data pre-negated saves some tiresome juggling between accumulator and storage.) If word 21 holdsn, the program will halt with the accumulator storingn!; as an example, we shall find 10!

11100000000000100000000000000000   0. -7 to c10101000000000010000000000000000   1. Sub. 2110100000000001100000000000000000   2. c to 510100000000000100000000000000000   3. -5 to c10100000000001100000000000000000   4. c to 500000000000000000000000000000000   5. generated at run time00000000000001110000000000000000   6. Stop00010000000000100000000000000000   7. -8 to c11111111111111111111111111111111   8. -111111111111111111111111111111111   9. -101111111111111111111111111111111  10. -201011111111111111111111111111111  11. -600010111111111111111111111111111  12. -2400010001111111111111111111111111  13. -12000001100101111111111111111111111  14. -72000001010001101111111111111111111  15. -504000000001010001101111111111111111  16. -4032000000001011011100101111111111111  17. -36288000000000100001010001001111111111  18. -362880000000000110101110111100110111111  19. -3991680000000000001000001100111011000111  20. -47900160001010000000000000000000000000000  21. 10

Standard ML

Recursive

fun factorial n =  if n <= 0 then 1  else n * factorial (n-1)

The following is tail-recursive, so it is effectively iterative:

fun factorial n = let  fun loop (i, accum) =    if i > n then accum    else loop (i + 1, accum * i)in  loop (1, 1)end

Stata

Mata has the built-infactorial function. Here are two implementations.

matareal scalar function fact1(real scalar n) {if (n<2) return(1)else return(fact1(n-1)*n)}real scalar function fact2(real scalar n) {a=1for (i=2;i<=n;i++) a=a*ireturn(a)}printf("%f\n",fact1(8))printf("%f\n",fact2(8))printf("%f\n",factorial(8))

Stax

{|F}

Non-builtin:

{R:*}

SuperCollider

Iterative

f = { |n| (1..n).product };f.(10);// for numbers larger than 12, use 64 bit float// instead of 32 bit integers, because the integer range is exceeded// (1..n) returns an array of floats when n is a floatf.(20.0);

Recursive

f = { |n| if(n < 2) { 1 } { n * f.(n - 1) } };f.(10);



Swift

Iterative

func factorial(_ n: Int) -> Int {return n < 2 ? 1 : (2...n).reduce(1, *)}

Recursive

func factorial(_ n: Int) -> Int {return n < 2 ? 1 : n * factorial(n - 1)}

Symsyn

fact if n < 1    return endif  * n fn fn - n call fact returnstart if i < 20    1 fn    i n    call fact    fn []    + i    goif endif

Tailspin

Iterative

templates factorial  when <0..> do    @: 1;    1..$ -> @: $@ * $;    $@ !end factorial

v0.5

factorial templates  when <|0..> do    @ set 1;    1..$ -> @ set $@ * $;    $@ !end factorial

Recursive

templates factorial  when <=0> do 1 !  when <0..> $ * ($ - 1 -> factorial) !end factorial

v0.5 only allows internal recursion through #

factorial templates  when <|=0> do 1 !  when <|0..> do $ * ($ - 1 -> #) !end factorial

Tcl

Works with:Tcl version 8.6
# tailcall optimization is standard in tcl8.6 proc fact { n { result 1. } } {    if { $n <= 1 } {        return $result    } else {        tailcall fact [expr {$n-1}] [expr {$n*$result}]    }}set  f [fact 10]puts $f
Output:
3628800.0
Works with:Tcl version 8.5

Use Tcl 8.5 for its built-in arbitrary precision integer support.

Iterative

proc ifact n {    for {set i $n; set sum 1} {$i >= 2} {incr i -1} {        set sum [expr {$sum * $i}]    }    return $sum}

Recursive

proc rfact n {     expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]} }

The recursive version is limited by the default stack size to roughly 850!

When put into thetcl::mathfunc namespace, the recursive call stays inside theexpr language, and thus looks clearer:

proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}}

Iterative with caching

proc ifact_caching n {    global fact_cache        tailcall fact [expr {$n-1}] [expr {$n*$result}]    if { ! [info exists fact_cache]} {        set fact_cache {1 1}    }    if {$n < [llength $fact_cache]} {        return [lindex $fact_cache $n]    }    set i [expr {[llength $fact_cache] - 1}]    set sum [lindex $fact_cache $i]    while {$i < $n} {        incr i        set sum [expr {$sum * $i}]        lappend fact_cache $sum    }    return $sum}

Using A Trampoline Function

A trampoline function runs each iteration in a loop to avoid too much recursion.

The computation function returns a list

{ "next" function name {arguments} }

or{ "value" final_value }

If the return is next the trampoline keeps"bouncing" the functionback up; if it is value it ends the loop.

# calls cmd with args# retpeatedly in scope aboveproc trampoline {cmd args} {    # thunk is  {cmd {arg1 arg2 arg3 ...} }    set result [uplevel 1 [concat $cmd $args]]    # split into vars    lassign $result type thunk    # loop     while {$type eq "next"} {        set result [uplevel 1 $thunk]    lassign $result type thunk    }    set final_value  $thunk        return $final_value}# return  { value final_value    }#     or  { next {cmd arg1 arg2} } proc factorial_step {n result} {    if {$n <= 1} {    set ret_value [list "value" $result]              } else {    # n-1    set next_n [expr {$n-1}]    # (n-1) * fact(n)    set next_result [expr {$n * $result}]    #  {func arg1 arg2}    set next_thunk [list factorial_step $next_n $next_result]    # Return the next step as a list    set ret_value [list "next" $next_thunk]     }    return $ret_value}# The execution is wrapped by the trampolineproc factorial {n} {    return [trampoline factorial_step $n 1]}set f [factorial 100]
Output:

(number line-wrapped)

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000


Performance Analysis

puts [ifact 30]puts [rfact 30]puts [ifact_caching 30]set n 400set iterations 10000puts "calculate $n factorial $iterations times"puts "ifact: [time {ifact $n} $iterations]"puts "rfact: [time {rfact $n} $iterations]"# for the caching proc, reset the cache between each iteration so as not to skew the resultsputs "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]"
Output:
265252859812191058636308480000000265252859812191058636308480000000265252859812191058636308480000000calculate 400 factorial 10000 timesifact: 661.4324 microseconds per iterationrfact: 654.7593 microseconds per iterationifact_caching: 613.1989 microseconds per iteration

Using the Γ Function

Note that this only works correctly for factorials that produce correct representations in double precision floating-point numbers.

Library:Tcllib(Package: math::special)
package require math::specialproc gfact n {    expr {round([::math::special::Gamma [expr {$n+1}]])}}

TI-57

The program stack has only three levels, which means that the recursive approach can be dispensed with.

Machine codeComment
Lbl 0C.tx=t1STO 0Lbl 1RCL 0×DszGTO 11=R/SRST
program factorial(x) // x is the display registerif x=0 then  x=1r0 = xloop    multiply r0 by what will be in the next loop  decrement r0 and exit loop if r0 = 0end loopcomplete the multiplication sequencereturn x!end programreset program pointer

TorqueScript

Iterative

function Factorial(%num){    if(%num < 2)        return 1;    for(%a = %num-1; %a > 1; %a--)        %num *= %a;    return %num;}

Recursive

function Factorial(%num){    if(%num < 2)        return 1;    return %num * Factorial(%num-1);}

TransFORTH

: FACTORIAL1 SWAP1 + 1 DOI * LOOP ;

TUSCRIPT

$$ MODE TUSCRIPTLOOP num=-1,12 IF (num==0,1) THEN  f=1 ELSEIF (num<0) THEN  PRINT num," is negative number"  CYCLE ELSE  f=VALUE(num)  LOOP n=#num,2,-1   f=f*(n-1)  ENDLOOP ENDIFformatnum=CENTER(num,+2," ")PRINT "factorial of ",formatnum," = ",fENDLOOP
Output:
-1 is negative numberfactorial of  0 = 1factorial of  1 = 1factorial of  2 = 2factorial of  3 = 6factorial of  4 = 24factorial of  5 = 120factorial of  6 = 720factorial of  7 = 5040factorial of  8 = 40320factorial of  9 = 362880factorial of 10 = 3628800factorial of 11 = 39916800factorial of 12 = 479001600

TAV

factorial (n) iterative:   p =: 1   ?# i =: from 2 upto n \ does nothing if n < 2     p =* i   :> pfactorial (n) recursive:   ? n <= 1      :> 1   :> n * factorial recursive n-1 \ test code main(parms):+   arg =: string parms[1] as integer else 100     print factorial arg iterative   print factorial arg recursive

TXR

Built-in

Via nPk function:

$ txr -p '(n-perm-k 10 10)'3628800

Functional

$ txr -p '[reduce-left * (range 1 10) 1]'3628800

UNIX Shell

Iterative

Works with:Bourne Shell
factorial() {  set -- "$1" 1  until test "$1" -lt 2; do    set -- "`expr "$1" - 1`" "`expr "$2" \* "$1"`"  done  echo "$2"}

Ifexpr uses 32-bit signed integers, then this function overflows afterfactorial 12.

Or inKorn style:

Works with:bash
Works with:ksh93
Works with:zsh
function factorial {  typeset n=$1 f=1 i  for ((i=2; i < n; i++)); do    (( f *= i ))  done  echo $f}

Recursive

These solutions fork many processes, because each level of recursion spawns a subshell to capture the output.

Works with:Almquist Shell
factorial (){  if [ $1 -eq 0 ]    then echo 1    else echo $(($1 * $(factorial $(($1-1)) ) ))  fi}

Or inKorn style:

Works with:bash
Works with:ksh93
Works with:pdksh
Works with:zsh
function factorial {  typeset n=$1  (( n < 2 )) && echo 1 && return  echo $(( n * $(factorial $((n-1))) ))}

C Shell

This is an iterative solution.csh uses 32-bit signed integers, so this alias overflows afterfactorial 12.

alias factorial eval \''set factorial_args=( \!*:q )\\@ factorial_n = $factorial_args[2]\\@ factorial_i = 1\\while ( $factorial_n >= 2 )\\@ factorial_i *= $factorial_n\\@ factorial_n -= 1\\end\\@ $factorial_args[1] = $factorial_i\\'\'factorial f 12echo $f# => 479001600

Uiua

Factorial = /×+1⇡

Ursa

Translation of:Python

Iterative

def factorial (int n)decl int resultset result 1decl int ifor (set i 1) (< i (+ n 1)) (inc i)set result (* result i)endreturn resultend

Recursive

def factorial (int n)      decl int z      set z 1      if (> n 1)              set z (* n (factorial (- n 1)))      end if      return zend

Ursala

There is already a library function for factorials, but they can be defined anyway like this. The good method treats natural numbers as an abstract type, and the better method factors out powers of 2 by bit twiddling.

#import natgood_factorial   = ~&?\1! product:-1^lrtPC/~& iotabetter_factorial = ~&?\1! ^T(~&lSL,@rS product:-1)+ ~&Z-~^*lrtPC/~& iota

test program:

#cast %nLtest = better_factorial* <0,1,2,3,4,5,6,7,8>
Output:
<1,1,2,6,24,120,720,5040,40320>

Uxntal

%newline { [ LIT2 0a -Console/write ] DEO }|18 @Console/write|100 #0900 &loopDUP #00 SWP factorial print/dec newlineINC GTHk ?&loopPOP2BRK@factorial ( n* -- n!* )    ORAk ?{ POP2 #0001 JMP2r }    DUP2 #0001 SUB2 factorial MUL2JMP2r@print/dec ( short* -- )#000a SWP2 [ LITr ff ]&get ( -- )SWP2k DIV2k MUL2 SUB2 STHPOP OVR2 DIV2 ORAk ?&getPOP2 POP2&put ( -- )STHr INCk ?{ POP JMP2r }[ LIT "0 ] ADD .Console/write DEO !&put
Output:
112624120720504040320

Verbexx

// ----------------// recursive method  (requires INTV_T input parm)// ----------------fact_r @FN [n] {      @CASE      when:(n <  0iv) {-1iv                 }      when:(n == 0iv) { 1iv                 }       else:           { n * (@fact_r n-1iv) } };// ----------------// iterative method  (requires INTV_T input parm) // ----------------fact_i @FN [n]{    @CASE       when:(n <  0iv) {-1iv }       when:(n == 0iv) { 1iv }      else:           {                        @VAR i fact = 1iv 1iv;                        @LOOP while:(i <= n) { fact *= i++ };                      }};            // ------------------// Display factorials// ------------------@VAR i = -1iv; @LOOP times:15{     @SAY «recursive  » i «! = » (@fact_r i) between:"";        @SAY «iterative  » i «! = » (@fact_i i) between:"";       i = 5iv * i / 4iv + 1iv;}; /]========================================================================================= Output:recursive  -1! = -1iterative  -1! = -1recursive  0! = 1iterative  0! = 1recursive  1! = 1iterative  1! = 1recursive  2! = 2iterative  2! = 2recursive  3! = 6iterative  3! = 6recursive  4! = 24iterative  4! = 24recursive  6! = 720iterative  6! = 720recursive  8! = 40320iterative  8! = 40320recursive  11! = 39916800iterative  11! = 39916800recursive  14! = 87178291200iterative  14! = 87178291200recursive  18! = 6402373705728000iterative  18! = 6402373705728000recursive  23! = 25852016738884976640000iterative  23! = 25852016738884976640000recursive  29! = 8841761993739701954543616000000iterative  29! = 8841761993739701954543616000000recursive  37! = 13763753091226345046315979581580902400000000iterative  37! = 13763753091226345046315979581580902400000000recursive  47! = 258623241511168180642964355153611979969197632389120000000000iterative  47! = 258623241511168180642964355153611979969197632389120000000000


Verilog

Recursive

module main;   function automatic [7:0] factorial;    input [7:0] i_Num;     begin      if (i_Num == 1)        factorial = 1;       else        factorial = i_Num * factorial(i_Num-1);    end  endfunction   initial    begin      $display("Factorial of 1 = %d", factorial(1));      $display("Factorial of 2 = %d", factorial(2));      $display("Factorial of 3 = %d", factorial(3));      $display("Factorial of 4 = %d", factorial(4));      $display("Factorial of 5 = %d", factorial(5));    endendmodule


VHDL

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;ENTITY Factorial ISGENERIC (Nbin : INTEGER := 3 ; -- number of bit to input number Nbou : INTEGER := 13) ; -- number of bit to output factorialPORT (clk : IN STD_LOGIC ; -- clock of circuitsr  : IN STD_LOGIC_VECTOR(1 DOWNTO 0); -- set and reset  N   : IN STD_LOGIC_VECTOR(Nbin-1 DOWNTO 0) ; -- max number     Fn  : OUT STD_LOGIC_VECTOR(Nbou-1 DOWNTO 0)); -- factorial of "n"    END Factorial ;ARCHITECTURE Behavior OF Factorial IS ---------------------- Program Multiplication -------------------------------- FUNCTION Mult ( CONSTANT MFa : IN UNSIGNED ;CONSTANT MI   : IN UNSIGNED ) RETURN UNSIGNED IS  VARIABLE Z : UNSIGNED(MFa'RANGE) ;VARIABLE U : UNSIGNED(MI'RANGE) ;BEGINZ := TO_UNSIGNED(0, MFa'LENGTH) ; -- to obtain the multiplicationU := MI ; -- regressive counter LOOP Z := Z + MFa ; -- make multiplicationU := U - 1 ; EXIT WHEN U = 0 ;END LOOP ; RETURN Z ;END Mult ; -------------------Program Factorial ---------------------------------------FUNCTION Fact (CONSTANT Nx : IN NATURAL ) RETURN UNSIGNED IS VARIABLE C  : NATURAL RANGE 0 TO 2**Nbin-1 ;VARIABLE I  : UNSIGNED(Nbin-1 DOWNTO 0) ;VARIABLE Fa : UNSIGNED(Nbou-1 DOWNTO 0) ;BEGIN C := 0 ; -- counter I :=  TO_UNSIGNED(1, Nbin) ;Fa := TO_UNSIGNED(1, Nbou) ;LOOPEXIT WHEN C = Nx ; -- end loop C := C + 1 ;  -- progressive couter Fa := Mult (Fa , I ); -- call function to make a multiplication I := I + 1 ; -- END LOOP ;RETURN Fa ;END Fact ;--------------------- Program TO Call Factorial Function ------------------------------------------------------TYPE Table IS ARRAY (0 TO 2**Nbin-1) OF UNSIGNED(Nbou-1 DOWNTO 0) ;FUNCTION Call_Fact RETURN Table ISVARIABLE Fc : Table ; BEGIN FOR c IN 0 TO 2**Nbin-1 LOOPFc(c) := Fact(c) ;END LOOP ;RETURN Fc ; END FUNCTION Call_Fact;CONSTANT Result : Table := Call_Fact ; ------------------------------------------------------------------------------------------------------------SIGNAL Nin : STD_LOGIC_VECTOR(N'RANGE) ;BEGIN    -- start of architectureNin <= N               WHEN RISING_EDGE(clk) AND sr = "10" ELSE       (OTHERS => '0') WHEN RISING_EDGE(clk) AND sr = "01" ELSE   UNAFFECTED;Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ;END Behavior ;

Vim Script

function! Factorial(n)  if a:n < 2    return 1  else    return a:n * Factorial(a:n-1)  endifendfunction

V (Vlang)

Updated to V (Vlang) version 0.2.2

Imperative

const max_size = 10fn factorial_i() {  mut facs := [0].repeat(max_size + 1)  facs[0] = 1  println('The 0-th Factorial number is: 1')  for i := 1; i <= max_size; i++ {    facs[i] = i * facs[i - 1]    num := facs[i]    println('The $i-th Factorial number is: $num')  }}fn main() {factorial_i()}

Recursive

const max_size = 10fn factorial_r(n int) int {  if n == 0 {    return 1  }  return n * factorial_r(n - 1)}fn main() {  for i := 0; i <= max_size; i++ {    println('factorial($i) is: ${factorial_r(i)}')  }}

Tail Recursive

const max_size = 10fn factorial_tail(n int) int {sum := 1return factorial_r(n, sum)}fn factorial_r(n int, sum int) int {  if n == 0 {    return sum  }  return factorial_r(n - 1, n * sum )}fn main() {  for i := 0; i <= max_size; i++ {    println('factorial($i) is: ${factorial_tail(i)}')  }}

Memoized

const max_size = 10struct Cache {mut:  values []int}fn fac_cached(n int, mut cache Cache) int {  is_in_cache := cache.values.len > n  if is_in_cache {    return cache.values[n]  }  fac_n := if n == 0 { 1 } else { n * fac_cached(n - 1, mut cache) }  cache.values << fac_n  return fac_n}fn main() {  mut cache := Cache{}  for n := 0; n <= max_size; n++ {    fac_n := fac_cached(n, mut cache)    println('The $n-th Factorial is: $fac_n')  }}
Output:
The 0-th Factorial is: 1The 1-th Factorial is: 1The 2-th Factorial is: 2The 3-th Factorial is: 6The 4-th Factorial is: 24The 5-th Factorial is: 120The 6-th Factorial is: 720The 7-th Factorial is: 5040The 8-th Factorial is: 40320The 9-th Factorial is: 362880The 10-th Factorial is: 3628800

Vyxal

Built-in

¡

Reduction

ɾƒ*

Recursive

λ0=[1|‹x*];

Wart

Recursive, all at once

def (fact n)  if (n = 0)    1    (n * (fact n-1))

Recursive, using cases and pattern matching

def (fact n)  (n * (fact n-1))def (fact 0)  1

Iterative, with an explicit loop

def (fact n)  ret result 1    for i 1 (i <= n) ++i      result <- result*i

Iterative, with a pseudo-generator

# a useful helper to generate all the natural numbers until ndef (nums n)  collect+for i 1 (i <= n) ++i    yield idef (fact n)  (reduce (*) nums.n 1)

WDTE

Recursive

let max a b => a { < b => b };let ! n => n { > 1 => - n 1 -> ! -> * n } -> max 1;

Iterative

let s => import 'stream';let ! n => s.range 1 (+ n 1) -> s.reduce 1 *;

WebAssembly

(module  ;; recursive  (func $fac (param f64) (result f64)    get_local 0    f64.const 1    f64.lt    if (result f64)      f64.const 1    else      get_local 0      get_local 0      f64.const 1      f64.sub      call $fac      f64.mul    end)  (export "fac" (func $fac)))
(module  ;; recursive, more compact version  (func $fac_f64 (export "fac_f64") (param f64) (result f64)    get_local 0 f64.const 1 f64.lt    if (result f64)      f64.const 1    else      get_local 0          get_local 0  f64.const 1  f64.sub        call $fac_f64      f64.mul    end  ))
(module  ;; recursive, refactored to use s-expressions  (func $fact_f64 (export "fact_f64") (param f64) (result f64)    (if (result f64) (f64.lt (get_local 0) (f64.const 1))      (then f64.const 1)      (else        (f64.mul          (get_local 0)          (call $fact_f64 (f64.sub (get_local 0) (f64.const 1)))        )      )    )  ))
(module  ;; recursive, refactored to use s-expressions and named variables  (func $fact_f64 (export "fact_f64") (param $n f64) (result f64)    (if (result f64) (f64.lt (get_local $n) (f64.const 1))      (then f64.const 1)      (else        (f64.mul          (get_local $n)          (call $fact_f64 (f64.sub (get_local $n) (f64.const 1)))        )      )    )  ))
(module  ;; iterative, generated by C compiler (LLVM) from recursive code!  (func $factorial (export "factorial") (param $p0 i32) (result i32)    (local $l0 i32) (local $l1 i32)    block $B0      get_local $p0      i32.eqz      br_if $B0      i32.const 1      set_local $l0      loop $L1        get_local $p0        get_local $l0        i32.mul        set_local $l0        get_local $p0        i32.const -1        i32.add        tee_local $l1        set_local $p0        get_local $l1        br_if $L1      end      get_local $l0      return    end    i32.const 1  ))

Wortel

Operator:

@fac 10

Number expression:

!#~F 10

Folding:

!/^* @to 10; or@prod @to 10

Iterative:

~!10 &n [  @var r 1  @for x to n    :!*r x  r]

Recursive:

@let {  fac &{fac n}?{    <n 2 n    *n !fac -n 1  }  ; memoized  facM @mem &n?{    <n 2 n    *n !facM -n 1  }  [[!fac 10 !facM 10]]}

Wrapl

Product

DEF fac(n) n <= 1 | PROD 1:to(n);

Recursive

DEF fac(n) n <= 0 => 1 // n * fac(n - 1);

Folding

DEF fac(n) n <= 1 | :"*":foldl(ALL 1:to(n));

Wren

Library:Wren-fmt
Library:Wren-big
import "./fmt" for Fmtimport "./big" for BigIntclass Factorial {    static iterative(n) {        if (n < 2) return BigInt.one        var fact = BigInt.one        for (i in 2..n.toSmall) fact = fact * i        return fact    }    static recursive(n) {        if (n < 2) return BigInt.one        return n * recursive(n-1)    }}var n = BigInt.new(24)Fmt.print("Factorial(%(n)) iterative -> $,s", Factorial.iterative(n))Fmt.print("Factorial(%(n)) recursive -> $,s", Factorial.recursive(n))
Output:
Factorial(24) iterative -> 620,448,401,733,239,439,360,000Factorial(24) recursive -> 620,448,401,733,239,439,360,000

x86 Assembly

Works with:nasm

Iterative

global factorialsection .text; Input in ECX register (greater than 0!); Output in EAX registerfactorial:  mov   eax, 1.factor:  mul   ecx  loop  .factor  ret

Recursive

global factsection .text; Input and output in EAX registerfact:  cmp    eax, 1  je    .done   ; if eax == 1 goto done  ; inductive case  push  eax  ; save n (ie. what EAX is)  dec   eax  ; n - 1  call  fact ; fact(n - 1)  pop   ebx  ; fetch old n  mul   ebx  ; multiplies EAX with EBX, ie. n * fac(n - 1)  ret.done:  ; base case: return 1  mov   eax, 1  ret

Tail Recursive

global factorialsection .text; Input in ECX register; Output in EAX registerfactorial:  mov   eax, 1  ; default argument, store 1 in accumulator.base_case:  test  ecx, ecx  jnz   .inductive_case  ; return accumulator if n == 0  ret.inductive_case:  mul   ecx         ; accumulator *= n  dec   ecx         ; n -= 1  jmp   .base_case  ; tail call

XL

0! -> 1N! -> N * (N-1)!

XLISP

(defun factorial (x)(if (< x 0)nil(if (<= x 1)1(* x (factorial (- x 1))) ) ) )

XPL0

func FactIter(N);       \Factorial of N using iterative methodint N;                  \range: 0..12int F, I;[F:= 1;for I:= 2 to N do F:= F*I;return F;];func FactRecur(N);      \Factorial of N using recursive methodint N;                  \range: 0..12return if N<2 then 1 else N*FactRecur(N-1);

YAMLScript

!YS-v0defn main(*ns):  each n ns:    say: "$n! -> $factorial(n)"defn factorial(x):  if x <= 2:    (x ||| 1)    (2 .. x).mul(*)
Output:
$ ys factorial.ys 0 1 2 3 4 5 6 7 80! -> 11! -> 12! -> 23! -> 64! -> 245! -> 1206! -> 7207! -> 50408! -> 40320

Zig

Works with:Zig version 0.11.0

Supports all integer data types, and checks for both overflow and negative numbers; returns null when there is a domain error.

pub fn factorial(comptime Num: type, n: i8) ?Num {    return if (@typeInfo(Num) != .Int)        @compileError("factorial called with non-integral type: " ++ @typeName(Num))    else if (n < 0)        null    else calc: {        var i: i8 = 1;        var fac: Num = 1;        while (i <= n) : (i += 1) {            const tmp = @mulWithOverflow(fac, i);            if (tmp[1] != 0)                break :calc null; // overflow            fac = tmp[0];        } else break :calc fac;    };}pub fn main() !void {    const stdout = @import("std").io.getStdOut().writer();    try stdout.print("-1! = {?}\n", .{factorial(i32, -1)});    try stdout.print("0! = {?}\n", .{factorial(i32, 0)});    try stdout.print("5! = {?}\n", .{factorial(i32, 5)});    try stdout.print("33!(64 bit) = {?}\n", .{factorial(i64, 33)}); // not valid i64 factorial    try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible    try stdout.print("34! = {?}\n", .{factorial(i128, 34)}); // will overflow}
Output:
-1! = null0! = 15! = 12033!(64 bit) = null33! = 868331761881188649551819440128000000034! = null

zkl

fcn fact(n){[2..n].reduce('*,1)}fcn factTail(n,N=1) {  // tail recursion   if (n == 0) return(N);   return(self.fcn(n-1,n*N));}
fact(6).println();var BN=Import("zklBigNum");factTail(BN(42)) : "%,d".fmt(_).println();  // built in as BN(42).factorial()
Output:
7201,405,006,117,752,879,898,543,142,606,244,511,569,936,384,000,000,000

The [..] notation understands int, float and string but not big int so fact(BN) doesn't work but tail recursion is just a loop so the two versions are pretty much the same.

Retrieved from "https://rosettacode.org/wiki/Factorial?oldid=396824"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2026 Movatter.jp