58
\$\begingroup\$

Task

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.

\$\endgroup\$

161 Answers 161

5
+150
\$\begingroup\$

Prolog (SWI), 61 bytes

0+1. N+F:-nth1(N,_,_),Y is N-1,Y+G,(F is G*N->1>0;F<G,!,0>1). 

Try it online!

Steffan's answer is much shorter at 28 bytes, but this predicate was created to be as general as possible. It can be used to:

  • Validate that N! = F (for example, 5+120 will succeed, 6+120 will fail)
  • Calculate N! (5+F will bind F to 120)
  • Calculate N from N! (N+120 will bind N to 5)
    • N+1 has both 0 and 1 as possible values
    • A non-factorial will fail the predicate
  • Generate all N, N! pairs

The last section feels like it can be golfed, especially as it has both 0>1 as always true and 0<1 as always false, but I've been staring at it for a while and can't figure out anything better. Pity that \+! doesn't work.

\$\endgroup\$
2
  • \$\begingroup\$ what's the nth1 for btw? \$\endgroup\$ Commented May 7, 2023 at 8:00
  • \$\begingroup\$ @ASCII-only That's for iterating over each possible value of N>0 to make it more generalised . If N is already given (as it is in this challenge), that just evaluates as true. \$\endgroup\$ Commented May 7, 2023 at 21:57
4
\$\begingroup\$

Brain-Flak, 52 bytes

<>(())<>{(({}[()]))({<>({})<><({}[()])>}{}<>{})<>}<> 

Try it online!

Posting my own Brain-Flak solution, which differs from the same size one from the older challenge.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You might want to move your Brainfuck answer too, as BF can't meet the performance requirement of the old challenge (which makes all BF answers there invalid). \$\endgroup\$ Commented Aug 25, 2020 at 1:20
4
\$\begingroup\$

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.

Befunge-93, 20 bytes

1&0>-#1:__\#0:#*_$.@ 

Try it online!

\$\endgroup\$
4
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ f=x=>x<1orx*f(x-1) seems to work just fine. \$\endgroup\$ Commented Aug 25, 2020 at 8:39
  • \$\begingroup\$ This seems like an interesting language. Is there more documentation than the GitHub Wiki? \$\endgroup\$ Commented Aug 25, 2020 at 8:45
  • \$\begingroup\$ @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 \$\endgroup\$ Commented Aug 25, 2020 at 11:13
4
\$\begingroup\$

Haskell, 17 bytes

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!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Doesn't simply f n=product[1..n] work for 17 bytes? \$\endgroup\$ Commented Aug 26, 2020 at 21:43
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Prolog (SWI), 28 bytes

N+X:-N>0,N-1+Y,X is Y*N;X=1. 

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Raku, 11 bytes

{[*] 1..$_} 

Try it online!

{ } : anonymous code block [ ] : reduction metaoperator * : multiplication 1..$_ : range from 1..input 
\$\endgroup\$
4
\$\begingroup\$

TypeScript Type System, 82 bytes

type X<A,B=A>=A extends`1${infer R}`?B extends`1${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.

\$\endgroup\$
4
\$\begingroup\$

Ly, 9 8 bytes

-1 thanks to cnamejj

R11[*f]p 

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.

\$\endgroup\$
2
  • \$\begingroup\$ It may be a terrible language, but it's fun. :) \$\endgroup\$ Commented Nov 12, 2021 at 10:52
  • \$\begingroup\$ heh... one byte less with this related program. :) R11[*f]p \$\endgroup\$ Commented Apr 22, 2024 at 6:13
3
\$\begingroup\$

Python 3.8, 23 21 bytes

Saved 2 bytes thanks to Bubbler!!!

import math math.perm 

Try it online!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ I think f= can be excluded from the byte count? \$\endgroup\$ Commented Aug 24, 2020 at 23:44
  • \$\begingroup\$ @Bubbler You get so used to things you forget what their orginal purpose was - thanks for the heads up! :D \$\endgroup\$ Commented Aug 24, 2020 at 23:55
  • \$\begingroup\$ What's the point of the math.perm line? I mean, sure, we use math.perm() in the footer, but you can take out that math.perm line and the code will still work. (Then again, maybe the import math line can just be placed in the header, which would leave... 0 bytes? Hm... maybe we should count math.perm.) \$\endgroup\$ Commented Aug 25, 2020 at 17:41
  • \$\begingroup\$ @J-L In function answers the whole point is to provide enough code to define a function that solves the challenge. Here the function is math.perm so job done. Leaving anything out doesn't provide a full solution. \$\endgroup\$ Commented Aug 25, 2020 at 17:52
  • \$\begingroup\$ Hmm I feel like excluding the f= is somehow wrong, maybe because the interface between the answer and the evaluation code is tightly coupled? Moving f= to the header only makes sense when the first line of code can be used as an expression without assignment, in this case we could wrap math.perm in a lambda and then import math to fit the usual pattern of excluding the assigned variable. If math.perm is allowed to be named in the evaluation code, we could look at the import math statement as a complete solution since it defines math.perm in the current scope. \$\endgroup\$ Commented Feb 7, 2022 at 4:56
3
\$\begingroup\$

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 
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 23 19 bytes

->n{Math.gamma n+1} 

-4 bytes using gamma function (Dingus).

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

Io, 20 bytes

method(\,\factorial) 

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Python 2, 38 bytes

i=n=1;exec"n*=i;i+=1;"*input();print n 

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Nice attempt. Note that the old challenge has a ton of non-builtin Python answers, the best being a 25-bytes function. \$\endgroup\$ Commented Aug 25, 2020 at 8:18
  • 3
    \$\begingroup\$ @Bubbler I just wanted to see what I could get without looking at the old ones \$\endgroup\$ Commented Aug 25, 2020 at 8:19
  • 1
    \$\begingroup\$ Nice, your exec this beats the while loop: TIO \$\endgroup\$ Commented Aug 25, 2020 at 9:57
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

Assembly (MIPS, SPIM), 108 bytes, 6*10 = 60 assembled bytes

main:li $v0,5 syscall li $a0,1 beqz $v0,e f:mul $a0,$a0,$v0 sub $v0,$v0,1 ble $v0,0,e b f e:li $v0,1 syscall 

Try it online!

Explanation

main: li $v0, 5 # set syscall code 5 syscall # Read an integer into v0 li $a0, 1 # register a0 = 1 beqz $v0, end # Handle $v0 = 0 case fact: # Main procedure: mul $a0, $a0, $v0 # a0 = a0 * v0 sub $v0, $v0, 1 # v0 = v0 - 1 ble $v0, 0, end # If v0 <= 0, jump to end b fact # Jump back to the start of the procedure end: # After-process: li $v0, 1 # Set sycall code 1 syscall # Output the number stored in a0 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ @640KB Sorry for the late response, it's fixed now. \$\endgroup\$ Commented Aug 26, 2020 at 1:17
3
\$\begingroup\$

Pepe, 57 bytes

3 bytes have been decreased from my Pepe factorial program.

rrEEReREEEEErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE 

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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 
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! \$\endgroup\$ Commented Sep 15, 2020 at 22:41
3
\$\begingroup\$

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)!) 
\$\endgroup\$
3
\$\begingroup\$

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 :)

\$\endgroup\$
4
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Feb 15, 2021 at 3:32
  • 1
    \$\begingroup\$ and you can save some bytes Try it online! \$\endgroup\$ Commented Feb 15, 2021 at 5:47
  • 1
    \$\begingroup\$ recursive via filter Try it online! \$\endgroup\$ Commented Feb 15, 2021 at 11:25
  • 1
    \$\begingroup\$ and filter f{$_ ?$_*(--$_|f):1} (27 bytes) with ternary operator for PS7 \$\endgroup\$ Commented Feb 15, 2021 at 11:30
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

Python 3, 61 50 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.

\$\endgroup\$
4
  • \$\begingroup\$ 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. \$\endgroup\$ Commented May 11, 2021 at 2:32
  • \$\begingroup\$ Also since n is used only once, you can pass int(input()) to range(...) directly. Try it online! \$\endgroup\$ Commented May 11, 2021 at 2:35
  • \$\begingroup\$ You can move the a*=i+1 to the same line as the for loop to save 2 bytes \$\endgroup\$ Commented May 11, 2021 at 5:39
  • \$\begingroup\$ You could just use import math;math.factorial(n) \$\endgroup\$ Commented Sep 2, 2022 at 9:27
3
\$\begingroup\$

Rockstar, 70 66 62 61 60 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)

\$\endgroup\$
2
  • \$\begingroup\$ Say F to Pay Respects \$\endgroup\$ Commented Sep 9, 2020 at 16:07
  • \$\begingroup\$ I'm tempted to rename F to X... \$\endgroup\$ Commented Sep 10, 2020 at 1:58
3
\$\begingroup\$

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 >> Jump to thread one if the current value is greater than zero 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 >= Jump to thread two if the value is greater than or equal to zero \/ 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 
\$\endgroup\$
3
\$\begingroup\$

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".

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

JavaScript, 19 bytes

f=n=>n?f(n-1n)*n:1n 

2 bytes longer than the other JS answers, but can safely calculate as high as 11190! instead of 18!, with anything higher exceeding the call stack size (tested on Node.js 18.6.0). the result has 40450 digits.

update: running with --stack-size=65536 allows me to calculate up to 95200!, resulting in 432625 digits. Trying to calculate any higher caused segmentation faults, no matter what I set the stack size to.

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.