The vanilla factorial challenge

Given a non-negative integer $$\n\$$, evaluate the factorial $$\n!\$$.

The factorial is defined as follows:

$$n!=\begin{cases}1 & n=0\\n\times(n-1)!&n>0\end{cases}$$

Rules

• All default I/O methods are allowed.
• Standard loopholes are forbidden.
• Built-ins are allowed.
• There is no time or memory limit.
• Giving imprecise or incorrect results for large inputs due to the limit of the native number format is fine, as long as the underlying algorithm is correct. Specifically, it is not allowed to abuse the native number type to trivialize the challenge, which is one of the standard loopholes.
• This is . Shortest code in bytes wins, but feel free to participate in various esolangs (especially the ones hindered by the restrictions of the former challenge).

Test cases

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600


Note: We already have the old factorial challenge, but it has some restrictions on the domain, performance, and banning built-ins. As the consensus here was to create a separate challenge without those restrictions so that more esolangs can participate, here it goes.

Also, we discussed whether we should close the old one as a duplicate of this, and we decided to leave it open.

Befunge-93, 20 19 bytes

&+#v:!_:
\@#<*_\:.#


Try it online!

Reposting more of my answers from the old challenge that didn't fit the requirements. This one didn't get up to 125!, at least with this interpreter.

Explanation:

&           Get the input
+          Add it to the current counter (initially 0)
:!_     Duplicate and check if it is zero
&+     :    If not, duplicate and repeat, but add the -1 from EOF to the input
#v:!      If it is, not the 0 into a 1, duplicate and go to the second line
This initialises the stack as n,n-1,n-2...,1,1,1
<        Start going left
\    _ :    Check if the second element on the stack is zero
*       If not, then multiply the top two elements
@#   \ .#  If it is, then print the factorial value and terminate


I believe this was actually my first answer on this site, with the below being the 20 byte version of the above.

1&0>-#1:__\#0:#*_$.@  Try it online! Bash, 13 bytes seq -s*$1|bc


Try it online!

• Hopefully you don't have a filename beginning with -s in the current directory. Aug 25, 2020 at 9:58

Funky 2, 22 18 bytes

Saved 4 bytes through ovs's optimization.

f=x=>x<1orx*f(x-1)


When x<1, returns 1 (Due to x<1 being truthy), Otherwise returns x*f(x-1), recursively getting the factorial/

Try it online!

• f=x=>x<1orx*f(x-1) seems to work just fine.
– ovs
Aug 25, 2020 at 8:39
• This seems like an interesting language. Is there more documentation than the GitHub Wiki?
– ovs
Aug 25, 2020 at 8:45
• @ovs Unfortunately I've not documented very well. And Worse, the TIO version is quite out-dated and lacks functionality. Good spot on the golf though Aug 25, 2020 at 11:13

f n=product[1..n]


Try it online!

• Thanks to 79037662 for suggesting it!

18 bytes

f 0=1
f x=x*f(x-1)


Try it online!

Or 19 bytes using fold.

f n=foldr(*)1[2..n]


Try it online!

• Doesn't simply f n=product[1..n] work for 17 bytes? Aug 26, 2020 at 21:43

Ly, 9 bytes

1fR[s*]pl


Try it online!

Ly, for some reason, doesn't have &* (product) like it does &+ (sum). I guess I forgot about it 3 years ago when I made this terrible language.

• It may be a terrible language, but it's fun. :) Nov 12, 2021 at 10:52

jq, 30 bytes

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


Try it online!

I spent a while trying to get while and foreach to do my bidding. Thankfully this existed.

jq, 38 bytes

def f(x):if x>0then x*f(x-1)else 1end;


Try it online!

A recursive function. reduce is a shorthand for a function like this.

• Nice! Can you please do another answer, as I can't start a +50 bounty on this because I've answered this question. Sep 2, 2021 at 20:40
• @emanresuA yeah, I noticed your js answer so I didn't bold it. I'll notify when i post my next one. Sep 3, 2021 at 2:32
• The second solution can be shortened to 33 bytes (and made much more efficient) if you allow def f: as follows: def f:if.>0then.*(.-1|f)else 1end
– peak
Jan 28 at 10:12

Regex 🐇 (RME / PCRE2 v10.35+), 12 bytes

^((?*x+)x)*$ Attempt This Online! - PCRE2 Try it on replit.com! - RegexMathEngine, in ECMAScript+(?*) mode Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.) ^ # tail = N = input number ( (?*x+) # Assert tail > 0; multiply the number of possible matches by tail x # tail -= 1 )* # Iterate the above as many times as possible, minimum zero$           # Assert tail == 0, so that the loop will have iterated N times


This solution uses (?*...) non-atomic lookahead. It (and any super-exponential function) is likely impossible to implement without some kind of non-atomic lookaround (which would be necessary for compatibility with other regex engines, e.g. Perl).

The problem is, without molecular lookahead, it's necessary to actually advance the cursor (subtract a value from $$\tail\$$) to try different possibilities in a way that scales with $$\n\$$. Without using molecular lookaround or advancing the cursor, the number of possibilities can only be multiplied by a constant, e.g. ()?()?()? or (|){3} to multiply them by $$\2^3\$$, or (||){9} to multiply them by $$\3^9\$$.

For example, without molecular lookahead, $$\2^n\$$ can be implemented as ^(x|x)*$ or ^(x+)*, $$\3^n\$$ as ^(x(||))*$ or ^((x+)*)+, and $$\17^n\$$ as ^(x((|){4}|))*$ or ^(((((x+)*)+)+)+)+. (The former method can be used for any $$\k^n\$$, and the latter for $$\{(2^k+1)}^n\$$.) Going off the rails a bit, there are also options like ^(((((x*)*)*)*)*)* for $$\\lceil{{80\over 17}154^n}\rceil+1\$$. But for a problem like Factorial, advancing the cursor by more than $$\1\$$ character per iteration wouldn't leave room for subsequent iterations to have access to the values of $$\tail\$$ they need. Note: I accidentally posted this on the wrong Factorial challenge on 2022-07-25. As the amount of time it takes is proportional to the result, it can't even calculate $$\12!\$$ in under a minute, so that is not the correct place for it. I have deleted it from there and reposted it here. Prolog (SWI), 28 bytes N+X:-N>0,N-1+Y,X is Y*N;X=1.  Try it online! tinylisp, 34 bytes (load library (q((n)(product(1to n  Try it online! (Code has +4 bytes for assigning the lambda function to a name.) Explanation Using the library functions product and 1to: (q Quote the following list, which can then be treated as a lambda function ((n) that takes a single argument n: (product Multiply together (if the list is empty, returns 1) (1to n)))) all numbers from 1 up to and including n  Zephyr, 72 bytes input n as Integer set f to 1 for i from 1to n set f to f*i next print f  Try it online! Same algorithm as my QBasic answer, just in a more-verbose syntax: If n is zero, the for loop does nothing and 1 is output. Otherwise, the for loop runs over i from 1 up to and including the input number, multiplying the result by each i. Ruby, 23 19 bytes ->n{Math.gamma n+1}  -4 bytes using gamma function (Dingus). Try it online! Python 2, 38 bytes i=n=1;exec"n*=i;i+=1;"*input();print n  Try it online! • Nice attempt. Note that the old challenge has a ton of non-builtin Python answers, the best being a 25-bytes function. Aug 25, 2020 at 8:18 • @Bubbler I just wanted to see what I could get without looking at the old ones Aug 25, 2020 at 8:19 • Nice, your exec this beats the while loop: TIO – xnor Aug 25, 2020 at 9:57 K (ngn/k), 6 bytes Solution: */1+!:  Try it online! Explanation: */1+!: / the solution !: / range 0..N 1+ / add 1 (vectorised) */ / product  Extra: • Also */-!-: for the same byte count. Pepe, 57 bytes 3 bytes have been decreased from my Pepe factorial program. rrEEReREEEEErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE  Try it online! Mornington Crescent, 3788 bytes 109 lines/ops Take Northern Line to Embankment Take Northern Line to Embankment Take District Line to Parsons Green Take District Line to Ravenscourt Park Take District Line to Embankment Take District Line to Embankment Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Turnham Green Take District Line to Victoria Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Turnham Green Take District Line to Notting Hill Gate Take District Line to Notting Hill Gate Take District Line to Embankment Take District Line to Embankment Take District Line to Stamford Brook Take District Line to Embankment Take Northern Line to Goodge Street Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Euston Take Victoria Line to Euston Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Moorgate Take Northern Line to Embankment Take Northern Line to Embankment Take Northern Line to Bank Take District Line to Hammersmith Take District Line to West Kensington Take District Line to Hammersmith Take District Line to South Kensington Take District Line to South Kensington Take Piccadilly Line to Bounds Green Take Piccadilly Line to South Kensington Take District Line to Ravenscourt Park Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take District Line to South Kensington Take District Line to South Kensington Take Piccadilly Line to Bounds Green Take Piccadilly Line to South Kensington Take Piccadilly Line to South Kensington Take District Line to Ravenscourt Park Take District Line to Temple Take District Line to West Kensington Take District Line to Bank Take District Line to Hammersmith Take District Line to West Kensington Take District Line to Hammersmith Take Piccadilly Line to Eastcote Take Piccadilly Line to Eastcote Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Eastcote Take Piccadilly Line to Ealing Common Take District Line to Ravenscourt Park Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take Piccadilly Line to Eastcote Take Piccadilly Line to Eastcote Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Eastcote Take Metropolitan Line to Eastcote Take Piccadilly Line to Ealing Common Take District Line to Ealing Common Take District Line to Bank Take District Line to Hammersmith Take District Line to West Kensington Take District Line to Stamford Brook Take District Line to Bank Take District Line to Hammersmith Take District Line to Stamford Brook Take District Line to Hammersmith Take District Line to Upminster Take District Line to Ravenscourt Park Take District Line to Upminster Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take District Line to Embankment Take District Line to Embankment Take Northern Line to Angel Take Northern Line to Embankment Take Northern Line to Embankment Take District Line to West Kensington Take District Line to Embankment Take Northern Line to Embankment Take Northern Line to Mornington Crescent  Commented version for some explanations: Take Northern Line to Embankment Take Northern Line to Embankment Take District Line to Parsons Green Take District Line to Ravenscourt Park # Save Input in Ravenscourt Take District Line to Embankment Take District Line to Embankment # Create -1 Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Turnham Green Take District Line to Victoria Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Turnham Green Take District Line to Notting Hill Gate Take District Line to Notting Hill Gate Take District Line to Embankment Take District Line to Embankment Take District Line to Stamford Brook # Save -1 in Stamford Brook Take District Line to Embankment # Create 1 Take Northern Line to Goodge Street Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Tottenham Court Road Take Northern Line to Tottenham Court Road Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Euston Take Victoria Line to Euston Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Northern Line to Moorgate Take Northern Line to Embankment Take Northern Line to Embankment Take Northern Line to Bank Take District Line to Hammersmith Take District Line to West Kensington # Save 1 in West Kensington # Save 1 as max value at Bounds Green, so we will later take the largest number between the input and 1 (to handle 0 as an input) Take District Line to Hammersmith Take District Line to South Kensington Take District Line to South Kensington Take Piccadilly Line to Bounds Green # Save 1 as max Take Piccadilly Line to South Kensington Take District Line to Ravenscourt Park # Get input Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take District Line to South Kensington Take District Line to South Kensington Take Piccadilly Line to Bounds Green Take Piccadilly Line to South Kensington Take Piccadilly Line to South Kensington Take District Line to Ravenscourt Park # If input is 0 -> now it is 1 Take District Line to Temple # Save in jumpstack # Take Current Result (West Kensington) as first argument to Chalfont & Latimer Take District Line to West Kensington Take District Line to Bank Take District Line to Hammersmith Take District Line to West Kensington Take District Line to Hammersmith Take Piccadilly Line to Eastcote Take Piccadilly Line to Eastcote Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Eastcote Take Piccadilly Line to Ealing Common # Take Current Value (Ravenscourt Park) as second argument to Chalfont & Latimer Take District Line to Ravenscourt Park Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take Piccadilly Line to Eastcote Take Piccadilly Line to Eastcote Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Eastcote Take Metropolitan Line to Eastcote Take Piccadilly Line to Ealing Common Take District Line to Ealing Common # Save the new result n*(n-1) as the current result at West Kensington Take District Line to Bank Take District Line to Hammersmith Take District Line to West Kensington # Put -1 (Stamford Brook) as the first argument of the addition in Upminster Take District Line to Stamford Brook Take District Line to Bank Take District Line to Hammersmith Take District Line to Stamford Brook Take District Line to Hammersmith Take District Line to Upminster # Put The current value (Ravenscourt Park) as the second argument of the addition in Upminster -> [decrement], save it in the current value Take District Line to Ravenscourt Park Take District Line to Upminster Take District Line to Bank Take District Line to Hammersmith Take District Line to Ravenscourt Park Take District Line to Hammersmith Take District Line to Embankment Take District Line to Embankment Take Northern Line to Angel # Check if we reached 0 as current value, if it equals 0, break the loop and continue here: Take Northern Line to Embankment Take Northern Line to Embankment Take District Line to West Kensington # Get the final result Take District Line to Embankment Take Northern Line to Embankment Take Northern Line to Mornington Crescent # Print and exit  Try it online! GolfScript, 9 bytes 1\~,{)*}/  Try it online! 1\ # Puts 1 under the input, this will be the acumulator ~, # Makes an array with numbers from 0 to (n-1) {)*} # This block goes to the top of the stack without being executed, when executed it increments and multiplies, this avoids multiplying by 0 and also multiplies by n / # Executes the previous block for each number in the array  • Welcome to Code Golf! Sep 15, 2020 at 22:41 Whispers v3, 25 bytes > Input >> 1! >> Output 2  Try it online! Squeezed pseudo code: >> Output ((Input)!)  Explanation: As always in Whispers, we run the last line first: >> Output 2  This line outputs the result from line 2: >> 1!  Use the result from line 1 to calculate the factorial (line 1)! > Input  Takes the first line of the input. So we get the squeezed pseudo code: >> Output ((Input)!)  PowerShell Core, 37 32 bytes param($a)1..($a+!$a)-join'*'|iex


Try it online!

Or recursive:

PowerShell Core, 37 36 bytes

filter f{if($_){$_*(--$_|f)}else{1}}  Try it online! All bytes reductions thanks to mazzy :) • The recursive version should include the part that makes it a named function f, because the submission wouldn't work without it. So it is 49 bytes. Feb 15, 2021 at 3:32 • and you can save some bytes Try it online! Feb 15, 2021 at 5:47 • recursive via filter Try it online! Feb 15, 2021 at 11:25 • and filter f{$_ ?$_*(--$_|f):1} (27 bytes) with ternary operator for PS7 Feb 15, 2021 at 11:30

Vyxal, 1 byte

¡


Try it Online!

Built-in factorial.

No built-in, 2 bytes

ɾΠ


Explanation:

    # Implicit input
ɾ   # Range [1, N]
Π  # Reduce by multiplication
# Implicit output


Try it Online!

Python 3, 6150 48 bytes

a=1
for i in range(int(input())):a*=i+1
print(a)


Try it online!

Thanks to Bubbler for shortening the code by 11 bytes. Another thanks to Jo King♦ for shortening the code by 2 bytes.

• You can remove the variable x and just use a*=i+1. And then you can write the for loop on a single line as for i in range(n):a*=i+1. Nice first answer. Also check out Tips for golfing in Python. May 11, 2021 at 2:32
• Also since n is used only once, you can pass int(input()) to range(...) directly. Try it online! May 11, 2021 at 2:35
• You can move the a*=i+1 to the same line as the for loop to save 2 bytes
– Jo King
May 11, 2021 at 5:39
• You could just use import math;math.factorial(n) Sep 2, 2022 at 9:27

Rockstar, 7066626160 55 bytes

listen to N
F's1
while N
let F be*N-0
let N be-1

say F


Try it here (Code will need to be pasted in)

• Say F to Pay Respects Sep 9, 2020 at 16:07
• I'm tempted to rename F to X... Sep 10, 2020 at 1:58

Quipu, 41 bytes

1&1&1&0&
[]--[][]
**2&0&/\
1&>=>>
>>\/
1&


Try it online!

This was written for the Learn you a Lang event (just like Aaron Miller's answer). This turned out surprisingly clean, with only 4 threads and no spaces.

Explanation

Quipu uses multiple threads (these are each column of two characters). The Scala interpreter I'm using here doesn't need spaces between threads, though the other interpreter on Esoteric IDE does need the separation, and actually supports the BigInt needed for factorials above the max integer value.

Anyway, thread zero is where we store the actual factorial value. All threads have the initial value of 0.

1&    Push 1
[]    Get the value of thread 1 (where the input number will be stored)
**    Multiply it by the current thread 0 value
1&    Push 1
1&    Otherwise push one to initialise the value (this happens on the first iteration)


After jumping, the current thread value is set to the value being checked, in this case, current value multiplied by thread one. When the current value is zero and the input has not yet been retrieved (and is also zero), we don't jump, setting the current value to the last knot (the 1).

Either way we move onto the next thread. Thread one is where we get the input and decrement it over each loop.

  1&     Push one
--     Subtract one from the current value
2&     Push two
\/     Otherwise push the input


Similar to thread zero, we initialise this value to the input if it was initially zero. Otherwise, we decrement the value. Next is thread two.

    1&     Push 1
[]     Get the value of thread one
0&     Push zero
>>     Jump back to thread zero if the value is still greater than zero


This loops back over the first two threads until the input has reached zero, multiplying the value of thread zero by each element in the range of 1 to the input. Once we're done, we finally execute thread three and terminate.

      0&    Push zero
[]    Get the value of thread zero
/\    And print


Knight, 25 bytes

;=x+=y 1P;W=x-x 1=y*x yOy


Try it online!

Ungolfed:

; = x +             x = sum of:
= y 1           y = 1 (passes through 1) and
PROMPT          a line from stdin (coerced to number)
; WHILE = x - x 1   while (x = x - 1) is nonzero:
= y * x y           y = x * y
OUTPUT y            print y


In Knight, coercion depends on the type of the first argument. So 1+"5" is 6 while "5"+1 is "51".

• Can be 24 bytes using the Trick lolol: ;=x+=y 1P;W=x-xT=y*x yOy Aug 15, 2022 at 15:19

Brachylog, 1 byte

ḟ


Try it online!

Also works with a fixed output and an unknown input, with decent performance.

No built-in, 3 bytes

⟦b×


Try it online!

Raku, 11 bytes

{[*] 1..$_}  Try it online! { } : anonymous code block [ ] : reduction metaoperator * : multiplication 1..$_   : range from 1..input


K (ngn/k), 6 bytes

*/1+!:


Try it online!

Explanations:

*/1+!:  Main function. Takes implicit input
!:  Create a range between [0..input-1] (the colon is used to indicate the language to
create the range instead of modulo)
1+    + 1 to each of the numbers, leaving us with [1..input]
*/      Fold and multiply


Apple Shortcuts, 3 2 actions

I was messing around with shortcuts, and found that it is a pretty functional programming language. There’s input, basic math, more complex math, lists and some basic list functions, dictionaries, some basic dictionary functions, statistical functions, and the ability to run code in SSH (plus some more advanced functions like hashing and Base64 conversion). The only problem that I can think of is that Shortcuts does not have any form of text-based interface, so instead of bytes, you have to count “actions”, which aren’t exactly “bytes” and are hard to compare with other answers in terms of length.

TLDR I messed with Apple Shortcuts and you should too.

-1 Action! It turns out, actions that need numbers have input built-in, so the “Get number from input” action was unnecessary.

Piet + ascii-piet, 34 bytes (2×17=34 codels)

tlqrjccskfeurmuuI  ???c?viqdltt ii


Try Piet online!

Piet + ascii-piet, 24 bytes (4×10=40 codels)

rmttlddqbDlbaltdmu?_ V??


Try Piet online!

Similar to below, but realized that I can remove 1 >. Also, using B2->B1 = I (which is a no-op) gave A2->B2 = D (which safely removes a 0) and a color sharing for 3. Luck based golfing?

Piet + ascii-piet, 27 bytes (5×11=55 codels)

rmttldqbdTl?dckmvfnnN TuDuu


Try Piet online!

The logic is the same as Parcly Taxel's.

Main loop (A1 -> A10 -> B9 -> B1 -> A1):

D * 2 1 r       Mostly no-op, just pushes [2 1]
I               Take input [2 1 n]; becomes a no-op afterwards
Invariant: [2 prod i]
d 1 -           [2 prod i i-1]
3 1 r d 1 > !   [2 i-1 prod i i<=1]
D               [2 i-1 prod i]; turn right at A2 if n <= 1
* 2 1 r         [2 i-1 prod*i]


After turn right at A2 (A2 -> E2):

x O <halt>      Discard i and print prod


The main trick here is to move the DP+ to the cell A2, and rotate the main loop accordingly. This works because most commands are no-op when there are not enough items on the stack yet.

TypeScript Type System, 82 bytes

type X<A,B=A>=A extends1${infer R}?B extends1${infer O}?${X<R>}${X<A,O>}:B:1


Try it online!

Quite similar to, but independently derived from noodle man's answer. I also stole their test harness.

This is basically the same as the JavaScript code f = (a, b = a) => a ? b ? f(a, b - 1) + f(a-1) : 0 : 1. The idea here is that we have two accumulators, a and b, where b starts at the value of a. We repeatedly decrement b and add f(a-1) to the total, which results in the factorial of a.