| Bytes | Lang | Time | Link |
|---|---|---|---|
| 023 | C gcc | 250818T095012Z | Toby Spe |
| 137 | Bespoke | 250120T034225Z | Josiah W |
| 024 | AArch64 machine code | 250610T150205Z | 鳴神裁四点一号 |
| 021 | h6 | 250412T190305Z | noodle p |
| 091 | Hatchback | 250205T013749Z | madeforl |
| 180 | jBasher2 | 250205T010032Z | madeforl |
| 008 | CASIO BASIC CASIO fx9750giii | 250126T213856Z | madeforl |
| nan | Piet + asciipiet | 220207T073833Z | Parcly T |
| 005 | jive | 241219T204721Z | Gleb |
| 035 | Setanta | 200826T113057Z | bb94 |
| 054 | sed 4.2.2 | 240422T173443Z | guest430 |
| 008 | Ly | 200826T062839Z | LyricLy |
| 130 | Gray Snail | 240422T051216Z | DLosc |
| 103 | [Assembly nasm | 240315T224125Z | vengy |
| 027 | Pascal | 240316T105507Z | Kai Burg |
| 001 | HP‑41C series | 240314T151517Z | Kai Burg |
| 005 | BQN | 240312T224226Z | DLosc |
| 036 | Swift | 230723T200253Z | macOSist |
| 041 | Gema | 231226T031058Z | manatwor |
| 099 | TypeScript Type System | 230506T221217Z | noodle p |
| 002 | Vyxal 3L | 231206T230903Z | noodle p |
| 005 | Uiua | 230928T082952Z | chunes |
| 082 | TypeScript Type System | 230928T031224Z | emanresu |
| 002 | Itr | 230807T185625Z | bsoelch |
| 043 | Thue++ | 230722T025557Z | Dadsdy |
| nan | 230307T100110Z | EzioMerc | |
| 003 | Desmoslang Assembly | 230529T152240Z | Dadsdy |
| 001 | Thunno 2 | 230528T185621Z | The Thon |
| 026 | Python | 230507T121913Z | The Empt |
| 094 | Python + sympy | 230416T084437Z | The Empt |
| 006 | minigolf | 230416T023050Z | user1176 |
| 042 | Fortran GFortran | 230307T102534Z | JSorngar |
| 001 | vemf | 230405T214623Z | mí |
| 029 | Python | 230405T161908Z | The Empt |
| 009 | Julia 1.0 | 230405T153803Z | Ashlin H |
| 084 | Nibbles | 230307T101538Z | sfieger |
| nan | Piet + asciipiet | 230307T043742Z | Bubbler |
| 009 | Arturo | 221113T181212Z | chunes |
| 001 | Pyt | 230302T103359Z | The Thon |
| nan | 230302T103216Z | The Thon | |
| 014 | Rattle | 220207T033721Z | d01 |
| 038 | Clojure | 221230T222355Z | Bob Jarv |
| 017 | Haskell | 200909T183701Z | iwilare |
| 014 | ><> | 221116T081540Z | Emigna |
| 002 | Apple Shortcuts | 221116T013212Z | joyofori |
| 006 | K ngn/k | 221114T082451Z | oeuf |
| 011 | Raku | 220906T224852Z | south |
| 061 | Prolog SWI | 220902T074704Z | Jo King |
| 028 | Prolog SWI | 220902T030345Z | naffetS |
| 012 | Regex 🐇 RME / PCRE2 v10.35+ | 220816T185356Z | Deadcode |
| 053 | Carbon | 220816T141517Z | Seggan |
| 014 | StackCell | 220815T192846Z | Starwort |
| 026 | Knight | 220814T223329Z | Sampersa |
| 001 | Brachylog | 220802T090100Z | Fatalize |
| 019 | JavaScript | 220802T072642Z | Leaf |
| 025 | Knight | 220802T014603Z | Bubbler |
| 028 | Knight | 220802T013928Z | naffetS |
| 510 | Pyramid Scheme | 220318T101637Z | emanresu |
| 002 | MATL | 200825T021207Z | Mukundan |
| 024 | APOL | 220207T141234Z | Ginger |
| 031 | Python 3 | 211115T155252Z | IAmQb |
| 024 | Cubix | 211112T111132Z | cnamejj |
| 080 | /// | 211111T115018Z | m90 |
| 036 | Wren | 211012T162255Z | chunes |
| 040 | Red | 211012T124940Z | chunes |
| 025 | Python 3 | 210929T072709Z | Jitse |
| 018 | Cascade | 210929T060528Z | Bubbler |
| 041 | Quipu | 210903T013627Z | Jo King |
| 010 | jq | 210902T233617Z | Michael |
| 079 | Scala 3 | 200911T140717Z | user |
| 064 | Quipu | 210902T150728Z | Aaroneou |
| 030 | jq | 210902T133820Z | Razetime |
| 055 | Rockstar | 200909T150130Z | Shaggy |
| 060 | PPL | 210902T115630Z | ophact |
| 048 | Python 3 | 210511T022515Z | r u even |
| 001 | Vyxal | 210422T205452Z | Aaroneou |
| 045 | Pinecone | 210422T164006Z | wasif |
| 056 | Python 3 | 210413T191704Z | Symmetr1 |
| 049 | M4 | 210412T101453Z | user1004 |
| 006 | Factor + math.factorials | 210331T032926Z | wasif |
| nan | Pxem | 210330T092649Z | user1004 |
| 032 | PowerShell Core | 210215T020619Z | Julian |
| 015 | Phooey | 210215T164910Z | EasyasPi |
| 078 | Assembly MIPS | 210215T164032Z | EasyasPi |
| 025 | Whispers v3 | 210211T021717Z | Michael |
| 035 | Tcl | 210213T014839Z | sergiol |
| 019 | Javascript ES6 | 210211T091203Z | emanresu |
| 011 | BRASCA v0.4 | 210122T112122Z | SjoerdPe |
| 012 | ARM Thumb2 | 210211T054535Z | EasyasPi |
| 037 | Kotlin | 210210T175902Z | grian |
| 027 | Python 3 | 210123T101950Z | nTerior |
| 016 | convey | 210122T102135Z | Jo King |
| 001 | Husk | 201014T152656Z | Razetime |
| 016 | Labyrinth | 200930T094939Z | Jo King |
| 050 | ink | 200925T181135Z | Sara J |
| 014 | Flurry nii | 200825T003447Z | Bubbler |
| 009 | GolfScript | 200915T165421Z | 2014MELO |
| 042 | C# | 200911T143356Z | Tomasz J |
| 002 | Arn | 200826T165536Z | ZippyMag |
| 026 | F# | 200826T134806Z | Brunner |
| 3788 | Mornington Crescent | 200828T154546Z | SomoKRoc |
| 056 | MiniFlak | 200828T155322Z | Nitrodon |
| 013 | x8616 / x87 machine code | 200825T013137Z | 640KB |
| 046 | Python 2 | 200827T032003Z | aidan062 |
| 106 | Shakespeare Programming Language | 200825T030524Z | Dingus |
| 030 | Forth gforth | 200827T132453Z | reffu |
| 014 | Scala 2.12 | 200827T100431Z | corvus_1 |
| 057 | Pepe | 200827T033453Z | u-ndefin |
| 017 | Haskell | 200825T212125Z | AZTECCO |
| 080 | Miniflak | 200826T014729Z | Pizgenal |
| 409 | ArnoldC | 200826T150506Z | Charlie |
| 027 | Rust | 200825T104733Z | Technoha |
| 150 | COW | 200825T154602Z | Dingus |
| 128 | Muriel | 200826T073633Z | Jo King |
| 108 | Assembly MIPS | 200825T020656Z | user9649 |
| 038 | PHP | 200825T190901Z | 640KB |
| 020 | Rust | 200825T185853Z | madlaina |
| 030 | C# Visual C# Interactive Compiler | 200825T181501Z | Netr |
| 006 | K ngn/k | 200825T131318Z | mkst |
| 020 | Perl 5 p | 200825T124158Z | Dom Hast |
| 005 | cQuents | 200825T123146Z | Stephen |
| 036 | Java | 200825T121700Z | jmizv |
| 005 | Pip | 200825T121208Z | Razetime |
| 036 | Lua | 200825T120137Z | val - di |
| 047 | ReRegex | 200825T112714Z | ATaco |
| 018 | Funky 2 | 200825T032813Z | ATaco |
| 091 | TSQL | 200825T103821Z | Glorfind |
| 011 | Wolfram Language Mathematica | 200825T065226Z | ZaMoC |
| 015 | R | 200825T090011Z | JDL |
| 004 | Burlesque | 200825T090337Z | Mintable |
| 030 | Elixir | 200825T081323Z | pxeger |
| 038 | Python 2 | 200825T080354Z | pxeger |
| 013 | Bash | 200825T025245Z | Mukundan |
| 001 | MathGolf | 200825T061955Z | Kevin Cr |
| 019 | Befunge93 | 200825T024015Z | Jo King |
| 004 | CJam | 200825T051946Z | Ethan Ch |
| 003 | Wolfram Language Mathematica | 200825T044727Z | Mukundan |
| 002 | Desmos | 200825T051534Z | Ethan Ch |
| 002 | Seriously | 200825T050229Z | Razetime |
| 020 | Io | 200825T042656Z | user9649 |
| 020 | Rattle | 200825T024749Z | d01 |
| 008 | Charcoal | 200824T235605Z | Neil |
| 002 | TIBASIC TI83 | 200825T032930Z | Dingus |
| 019 | Ruby | 200825T022324Z | Razetime |
| 001 | J | 200824T225849Z | Jonah |
| 001 | Japt | 200825T021147Z | Mukundan |
| 056 | brainfuck | 200825T020143Z | Jo King |
| 052 | BrainFlak | 200825T011416Z | Jo King |
| 072 | Zephyr | 200825T005803Z | DLosc |
| 037 | QBasic | 200825T003328Z | DLosc |
| 021 | C gcc | 200825T002215Z | Sisyphus |
| 008 | Google Sheets / Excel / Numbers | 200825T002156Z | water_gh |
| 029 | Retina | 200825T001648Z | Neil |
| 034 | tinylisp | 200824T235504Z | DLosc |
| 021 | Python 3.8 | 200824T234231Z | Noodle9 |
| 065 | SNOBOL4 CSNOBOL4 | 200824T234149Z | Giuseppe |
| 017 | JavaScript Node.js | 200824T233952Z | Scott |
| 019 | MAWP | 200824T231234Z | lyxal |
| 001 | Jelly | 200824T231111Z | lyxal |
| 001 | 05AB1E | 200824T231003Z | lyxal |
| 002 | Pyth | 200824T230702Z | Scott |
| 004 | Keg | 200824T225746Z | lyxal |
Bespoke, 137 bytes
when I speak,I am real excited
words go BANG!as ecstatic speaking continues
it brings everyone entirely up
BANG!exclaim,get in a frenzy,u
Multiplies 1 by each number from N down to 1 (not multiplying at all if N is 0).
AArch64 machine code, 24 bytes
Completely port of ARM Thumb-2 answer except input and output are registers x1, x0:
Disassembly of section .text:
0000000000000000 <f>:
0: d2800020 mov x0, #0x1 // #1
4: b4000081 cbz x1, 14 <f+0x14>
8: 9b017c00 mul x0, x0, x1
c: d1000421 sub x1, x1, #0x1
10: b5ffffc1 cbnz x1, 8 <f+0x8>
14: d65f03c0 ret
Source
/// fn (x1: u64) x0: u64
.globl f
f:
mov x0,1
cbz x1,99f
1:
mul x0,x0,x1
sub x1,x1,1
cbnz x1,1b
99:
ret
How I tested on Termux
$ cat main.c
#include <stdio.h>
#include <stdlib.h>
unsigned long long f(int, unsigned long long);
int main(int argc, char **argv) {
unsigned long long x = strtoull(argv[1], NULL, 10);
printf("%llu\n", f(0, x));
}
$ clang main.c f.s
$ for x in $(seq 0 12); do printf "%2d => " "$x"; ./a.out "$x"; done
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
$
h6, 21 bytes
{1$range!{1+*}lfold!}
Explanation:
1$ # put 1 behind n
range! # take the range 0..n
{1+*}lfold! # fold the range, starting at 1, by
# multiplying the accumulator by one plus
# the value from the range.
Alternatively, with just plain recursion, 22 bytes:
f:{.1>{;1}{.1-f!*}l?!}
Hatchback, 91 bytes
16 0 10 2 0 8 8 2 6 8 0 1 0 1 1 0 9 1 2 0 9 3 0 9 4 1 0 10 2 0 7 2 9 6 2 65281 17 1 1 65535
un-golfed:
16 0
10 2 0
8 8 2
6 8 0 1
0 1 1
0 9 1
2 0 9
3 0 9
4 1 0
10 2 0
7 2 9
6 2 65281 17
1 1
65535
jBasher2, 180 bytes
create a with type number
create b with type number
ask for input
set that to a
set 1 to b
while a > 1
multiply b by a
set that to b
subtract a by 1
set that to a
endwhile
output b
very self explanatory
CASIO BASIC (CASIO fx-9750giii), 8 bytes
?→A
A!
builtin lol
4 bytes
this is cheating a little bit
Ans!
you gotta put the number in the Ans variable before running the program
jive, 5 bytes
*`,!↓
Alternatively you can use the ↑. But that prints the whole stack
jive using jive-online, 3 bytes
*!↓
Since JavaScript has automatic conersion. This works
sed 4.2.2, 54 bytes
h # copy number to hold space
: # define label ''
x;s/&//;x # decrement hold space
G # append hold space to pattern space after newline
s/(&+)\n(&+)/sed 's%\1%\2%'<<<'\1'/e # multiply two numbers seperated by a newline
t # if a swap happened, branch to ''
honestly surprised no one's done a sed answer here yet. takes input in unary &s. TIO link comes with decimal conversion header and footer for easy verification.
the multiplication is done by using the fact that an & in the regex half of a s/// command matches an & but an & in the replace half means 'the whole match'. so s/&&&/&&/ actually means 'replace &&& with itself twice'; e.g. multiplication by two.
Ly, 9 8 bytes
-1 thanks to cnamejj
R11[*f]p
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.
Gray Snail, 130 bytes
INPUT n
POP f 1
F
POP p
POP i [n]
M
POP p _[p][f]
GOTO [i]
POP i [i]
GOTO M
POP f _[p]
POP n [n]
GOTO F 1 []
OUTPUT [f]
Takes input and produces output in unary (using 1s).
Try it here! (Paste the code, then click Compile Code, then click Execute Program, then enter your input and click Set Input.)
Ungolfed, with comments
INPUT num
"Set factorial = 1"
POP factorial _ 1
fact_loop:
"Multiply factorial by num using loop counter i, storing result in product"
"Set product = empty"
POP _ product _
"Set i = one less than num"
POP _ i [num]
mult_loop:
"Concatenate factorial to product"
POP _ product _[product][factorial]
"If i is empty, exit loop"
GOTO mult_done: "" [i]
"Decrement i"
POP _ i [i]
GOTO mult_loop:
mult_done:
"Set factorial = product"
POP _ factorial _[product]
"Decrement num, storing 1 in x if there was anything there to decrement"
POP x num [num]
"If there was, loop"
GOTO fact_loop: 1 [x]
OUTPUT [factorial]
Astute readers may notice that the outer loop runs one more time than you might expect. Despite the fact that num is zero on this last loop, it's not a problem because my multiplication algorithm doesn't work for multiplying by zero and leaves factorial unchanged.
[Assembly (nasm, x64, Linux)], 103 bytes
4c89c0e84a0000006683f800770366ffc048be0000000000000000b90a00
00004831d2f7f180c23066ffce88166683f80075ed66ffc066bf010048ba
00000000000000004829f20f0549ffc04983f80d7cae5083f801740c66ff
c8e8f2ffffff48f724244159c3
How it works
fact.asm
c:mov rax,r8
call f ; <---- Call factorial f()
cmp ax,0
ja x
inc ax
x:mov rsi,n ; <---+
mov ecx,10 ; |
l:xor rdx,rdx ; |
div ecx ; | Convert factorial to ASCII
add dl,48 ; |
dec si ; |
mov[rsi],dl ; |
cmp ax,0 ; <---+
jnz l
inc ax ; <---+
mov di,1 ; |
mov rdx,n+1 ; | Write factorial to stdout
sub rdx,rsi ; |
syscall ; <---+
inc r8
cmp r8,13 ; <---- Loop [0,12]
jl c
f:push rax ; <---+
cmp eax,1 ; |
jz e ; |
dec ax ; | Compute factorial EAX (in/out)
call f ; |
mul qword[rsp] ; |
e:pop r9 ; |
ret ; <---+
section .data
resb 9
n: db 10
Build Commands
nasm -f elf64 fact.asm -o fact.o
ld fact.o -o fact
objcopy --dump-section .text=text.bin fact.o
xxd -p text.bin > text.hex
Pascal, 27 B
The source code is split into a left half containing the boilerplate for a complete Pascal program, and right half containing the necessary step to evaluate \$n!\$ (i. e. the task).
Only the extra bytes necessary to achieve the task are counted.
{ boilerplate }{ necessary for evalution }
program factorial(input, output);
var
n ,i
:integer;
begin
readLn(input, n); for i≔2 to n−1 do n≔i*n
;writeLn(output, n)
end.
The built‑in data type integer comprises (at least) the range −maxInt through +maxInt inclusive.
The value of the built‑in constant maxInt is implementation‑defined.
Today, it is usually \$2^{63}-1\$, so you can calculate up to \$20!\$.
Remember that in Pascal for‑loop limits are inclusive, so you subtract \$1\$ from \$n\$.
This is similar to the limits in mathematical notation \$\prod\$ and \$\sum\$.
HP‑41C series, 1 B
Place \$n\$ into the X register (that is the top of the stack) and XEQ (execute) the built‑in command
FACT
\$n!\$ is now in the X register and \$n\$ in the L (“last X”) register.
The operation reports a DATA ERROR in case of negative or non‑integral arguments, and an OUT OF RANGE error for \$n \ge 70\$.
You can ignore “out of range” errors by setting flag 24 (SF 24).
If flag 24 is set, the operation is successful and yields 9.999999999 × 1099 as an “approximation”.
BQN, 5 bytes
×´1+↕
Explanation
Same as chunes's Uiua answer, just different syntax.
×´1+↕
↕ Range from 0 to argument - 1
1+ Add 1 to each
×´ Fold on multiplication
Swift, 37 36 bytes
var f={$0<1 ?1:(1...$0).reduce(1,*)}
Self-explanatory. Call it as f(n).
Gema, 41 characters
f:*=@cmpi{*;0;;1;@mul{@f{@sub{$0;1}};$0}}
Assuming a domain can be considered equivalent of a function.
(Being pure text processing utility, no way to calculate up to 125! to qualify for the old challenge.)
Sample run:
bash-5.2$ gema '*=@f{*};f:*=@cmpn{*;0;;1;@mul{@f{@sub{$0;1}};$0}}' <<< 12
479001600
TypeScript Type System, 98 99 bytes
type X<A,B=A>=B extends`1${infer R}`?R extends""?A:B extends A?X<B,X<R>>:`${A&string}${X<R,A>}`:"1"
Try it at the TypeScript playground
+1 byte to make X<0> work properly
I/O is unary strings.
Go check out emanresu A's really clean golf of this! It uses pretty much the same formula but the execution is really great.
It took me a little over an hour to come up with and golf. It's pretty hard to explain but the gist of it is that X<A> does the factorial, and X<A,B> does multiplication. It figures out which is being used by making B default to A if not specified, and checking if B extends A. I was able to get it so short by combining the types for factorial and multiplication, since they shared a lot of boilerplate.
I also wrote a version that uses decimal I/O for 184 175 bytes:
//@ts-ignore
type X<A,B=[]>=A extends 1[]?B extends[1,...infer R]?R extends[]?A:B extends A?X<A,X<R,R>>:[...A,...X<R,A>]:[1]:B extends{length:A}?X<B,B>["length"]:X<A,[...B,1]>
Try it at the TypeScript playground
@tjjfvi showed me this spectacular 153 byte version with I/O in decimal:
//@ts-ignore
type M<A,B,N=[]>=A extends[0,...infer A]?M<A,B,[...N,...B]>:N;type F<N,X=[],A=[0],L="length">=X[L]extends N?A[L]:F<N,[0,...X],M<[0,...X],A>>
Vyxal 3L, 2 bytes
/*
Fold / the input by multiplication *. Fold treats whole numbers as the range from 1 to n.
The factorial built-in is 4 bytes: fact
Uiua, 5 bytes
/×+1⇡
⇡ # create range [0..input)
+1 # amend it to [1..input]
/× # reduce by multiplication
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
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.
Thue++, 43 bytes
^(x*)x!::=$1!/$1
^((!+)/+x*)x::=$1$2
/!::=!
Input is on the state, in the form of some number of xs followed by an exclamation mark, output is on the state in the form of a number of exclamation marks.
Alternate idea that I'm not sure if allowed because the output has a number of slashes that arent part of the output total, 37 bytes:
^(x*)x!::=$1!/$1
^(([/!]+)x*)x::=$1$2
All answers works correctly for 0 only in Firefox
JavaScript, 29 bytes
- Without recursion
- Expects
Numbertype - Max value is
170. If above outputsInfinity
n=>eval('p=1;while(n)p*=n--')
f=n=>eval('p=1;while(n)p*=n--')
;[
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
170, // 7.257415615308004e+306
171, // Infinity
].forEach(n=>document.write(n + ' - ' + f(n), '<br>'))
JavaScript, 30 bytes
- Without recursion
- Expects
BigInttype - In theory there is no max value. In practice it depends on implementation
n=>eval('p=1n;while(n)p*=n--')
f=n=>eval('p=1n;while(n)p*=n--')
;[
0n, // 1
1n, // 1
2n, // 2
3n, // 6
4n, // 24
5n, // 120
6n, // 720
7n, // 5040
8n, // 40320
9n, // 362880
10n, // 3628800
11n, // 39916800
12n, // 479001600
170n, // 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000
171n, // 1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000
].forEach(n=>document.write(n + ' - ' + f(n), '<br>'))
JavaScript, 33 bytes
- Without recursion
- Expects
NumberorBigInttype - Max value for type
Numberis170. In theory there is no max value for typeBigInt
n=>eval('p=++n/n;while(--n)p*=n')
f=n=>eval('p=++n/n;while(--n)p*=n')
;[
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
170, // 7.257415615308004e+306
171, // Infinity
0n, // 1
1n, // 1
2n, // 2
3n, // 6
4n, // 24
5n, // 120
6n, // 720
7n, // 5040
8n, // 40320
9n, // 362880
10n, // 3628800
11n, // 39916800
12n, // 479001600
170n, // 7257415615307998967396728211129263114716991681296451376543577798900561843401706157852350749242617459511490991237838520776666022565442753025328900773207510902400430280058295603966612599658257104398558294257568966313439612262571094946806711205568880457193340212661452800000000000000000000000000000000000000000
171n, // 1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000
].forEach(n=>document.write(n + ' (' + typeof n + ') - ' + f(n), '<br>'))
Desmoslang Assembly, 3 Bytes
I!OT
Explanation: Takes input to Command, adds an exclamation mark for factorial, outputs it, and loops infinitely at the end.
Thunno 2, 1 byte
w
Attempt This Online! Built-in.
Thunno 2, 2 bytes
Rp
Attempt This Online! Product of range.
Python, 26 Bytes
import math
math.factorial
Uses the built-in function from the built-in module math.
Python + sympy, 94 Bytes
from sympy import *
x=Symbol("x")
i=int(input())
e=x**i
for y in range(i):
e=diff(e)
print(e)
Requires you to do pip install sympy in the command prompt, as this isn't a built-in module. Uses a calculus approach to calculate factorials.
minigolf, 6 bytes
1i,n*_
Explanation
1 Push 1
i Push input
, Repeat input times ([1..n]):
n* Muliply tos by curr. item
_ end repeat
implicit output
Fortran (GFortran), 51 42 bytes
We abuse that variables (and functions) beginning with i,j,k,l,m or n are assumed to be (or return) integers, and that all other objects are assumed to be (or return) reals to create this function that generates a list of integers and multiplies them together into a another integer. It breaks at i=13.
function k(i)
k=product((/(j,j=1,i)/))
end
vemf, 1 byte
!
Falls back to \$\Gamma\left(\alpha+1\right)\$ if \$\alpha\notin\mathbb Z\$
In the online interpreter this works (returns values other than ■/0/-0/inf) for \$-178.9999999999999\le\alpha\le170.6243769563\$ and \$\alpha\notin\mathbb Z^-\$ (set of negative integers)
Python, 34 29 Bytes
x=lambda a:a and a*x(a-1)or 1
lambda is good at shortening code!
-5 from TheThonnu
Nibbles, 8 nibbles (4 bytes)
? $ `*,$ 1
Explanation
? $ `*,$ 1 #
----------------------------------------
? $ # if arg1
# equals truthy (<0)
`* # product
,$ # range 1..arg1
# else
1 # 1
Piet + ascii-piet, 24 bytes (4×10=40 codels)
rmttlddqbDlbaltdmu?_ V??
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
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.
Thunno, \$ 1 \log_{256}(96) \approx \$ 0.82 bytes
F
Attempt This Online! or verify \$0!\$ to \$10!\$.
Builtins FTW.
Rattle, 14 bytes
|F0:s[1F]-F0*~
There's already a Rattle answer here by me but this approach is completely different. Not only does this answer use the shiny new interpreter, but it takes advantage of the fact that recursion was recently implemented in Rattle!
Explanation
| parses the user's input
F0 calls local function 0
: (separator between the main method and local function 0)
s save the current value to local memory slot 0 (local to only this instance of F0)
[1 ] if the value is equal to 1, then:
F return (returns 1)
- subtract 1 from the current value
F0 recursively call function 0 with the current value as a parameter
*~ multiply the result of function 0 by the value stored in local memory
(the result of the multiplication is returned)
Rattle is able to process factorials up to 170! with no loss in precision.
Haskell, 17 characters
f n=product[1..n]
Bonus reference: "The Evolution of a Haskell Programmer" by Fritz Ruehr
Try it online!
><>, 14 bytes
1$:@?!n$:1-@*!
Explanation
1 # initialize product as 1
$:@?!n # if the current counter (starts as n) is 0, print the product
$:1-@ # subtract 1 from the counter for the next iteration
* # multiply current counter with product
! # skip the product initialization for the next iteration
Apple Shortcuts, 3 2 actions
Try it for yourself: (Only works on iPads and iPhones, sadly.)
Paste this into Safari (Chrome doesn’t work): https://www.icloud.com/shortcuts/58b14330f7ea4fc18ed4849b15cdacc9
Select “Get Shortcut”
Go to Shortcuts
Click “Codegolf #1”
It will run.
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.
K (ngn/k), 6 bytes
*/1+!:
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
Raku, 11 bytes
{[*] 1..$_}
{ } : anonymous code block
[ ] : reduction metaoperator
* : multiplication
1..$_ : range from 1..input
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).
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+120will succeed,6+120will fail) - Calculate
N!(5+Fwill bindFto120) - Calculate
NfromN!(N+120will bindNto5)N+1has both0and1as 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.
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.
Carbon, 53 bytes
fn f(x:i32)->i32{return if(x==0)then 1else x*f(x-1);}
Here is a full program for testing at the above site:
package c api;
fn f(x:i32)->i32{return if(x==0)then 1else x*f(x-1);}
fn Main() -> i32 {
return f(5);
}
StackCell, 14 bytes
Uses this input format and this output format
The below code uses the Unicode control character glyphs [U+24XX] to represent ASCII unprintable control characters embedded in the source code
[the input is implicitly pushed to the stack before the program begins]
{'␁}[}*'␁}-{}]
[the output is left as the sole value on the stack after the program ends]
For standard I/O (i.e. stdin and stdout), the following snippet can be used to place the input on the stack (for 21 bytes):
'0'␁['0x-x'
*+@:'
-]`
and for output (26 bytes):
:[:'
x%'0+{X}X'
x/:]X:[:;]
For the complete program using stdin/stdout only, that means a total of 61 bytes:
'0'␁['0x-x'
*+@:'
-]`{'␁}[}*'␁}-{}]:[:'
x%'0+{X}X'
x/:]X:[;:]
Brachylog, 1 byte
ḟ
Also works with a fixed output and an unknown input, with decent performance.
No built-in, 3 bytes
⟦b×
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.
Knight, 25 bytes
;=x+=y 1P;W=x-x 1=y*x yOy
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".
Pyramid Scheme, 510 bytes
^ ^ ^
/ \ / \ / \
/set\ / \ /out\
^-----^ /loop \-----^
/a\ /]\ ^-------^ /b\
--- ^---^ /a\ -^ ---
/ \ /#\--- /]\
/set\---^ ^---^
^-----^ / \ / \ -^
/b\ ^-/ \ /set\ -^
--- ^-/line \ ^-----^ -^
/1\-------/b\ ^- / \
--- --- /*\ /set\
^---^-----^
/b\ /a\ /-\
--- --- ^---^
/a\ /1\
--- ---
It works!
I spent way too long debugging this. There's a lot of empty space which I can't seem to get rid of.
This is basically the following pseudocode:
a = input
b = 1
while a
b *= a
a -= 1
print b
APOL, 24 bytes
⊕(ƒ(-(⧣ 1) *(⋒ -(⋒ ∈))))
Explanation:
⊕( Sum of list
ƒ( List-builder for
-( Subtract
⧣ Integer input
1
)
*( Multiply
⋒ For iterator (what's being iterated through)
-( Subtract
⋒ For iterator
∈ Loop counter
)
)
)
)
Cubix, 24 bytes
I:;.^!^u.>($.sr*u..;uO;@
And here's a link to the Cubix online interpreter you can run in "debug" mode if you want to see the IP as it moves around the cube the code on.
http://ethproductions.github.io/cubix/?code=STo7Ll4hXnUuPigkLnNyKnUuLjt1TztA&input=NgoK&speed=6
I find it hard to explain code in this language, since the directions the code takes a confusing (since it's running through code wrapped around a cube). The size of the cube used varies based on the length of the code. In this case each side has 4 characters.
Here goes...
I:;.^!^u.>($.sr*u..;uO;@
^ - code starts here, change IP to "up"
I: - read a number from STDIN, duplicate it on stack
> - change IP to "right" (start of loop)
( - decrement top of stack
$ - skip the next instruction
^ - SKIPPED
! - if top of stack not 0, skip next instruction
^ - TRUE, change IP to "up" (exit path 0)
u - FALSE, IP does a "u turn"
* - multiple top two entries on the stack
r - rotate top three stack entries twice
s - flip the top two entries on the stack
; - delete the top of stack
u - IP does a "u turn", (end of loop)
; - exit path 1, delete top of stack
I - exit path 2, read STDIN as number onto stack
$ - exit path 3, skip next instruction
; - exit path 4, SKIPPED
; - exit path 5, delete top of stack
u - exit path 6, IP makes a "u turn"
O - exit path 7, output top of stack as a number
@ - exit path 8, halt program
///, 80 bytes
/!1/1!//!/S'SS'.'//1/S.B'S.B|B'SS.B|S|.SS'B|S'SS|B.SxBxSSxBxS|B..S//B/\\//S/\//!
Takes input in unary as 1s appended to the program. Produces output in unary as .s.
The program sends the ! to the end of the input, then makes several more substitutions. After completing the substitutions that exist in the initial program, each 1 from the input has been replaced with the following "1 code" (line breaks added for clarity):
/.\"/.\|\"/
/.\|/|./
/"\|/"/
/|\./x\x/
/x\x/|\../
and after that, /'//'.'.
Each copy of the "1 code" multiplies the number of full stops between the single quotes by 1, then increases the multiplier of the subsequent copies by 1. Many backslashes have been used to ensure that the rest of the code is not modified by earlier copies' execution.
The multiplication is done by adding a | at the end, then moving it left, replacing each . it passes with ., then removing it. To increase the multiplier, |. is changed to |.., with the intermediate step of xx.
Finally, the last substitution removes the single quotes, and the result is printed.
Red, 40 bytes
f: func[n][either n = 0[1][n * f n - 1]]
I'm surprised there are no Red answers here yet. I'm still pretty new to Red, so there may be golf potential here. But I condensed it as much as I could (all the whitespace is necessary). It's the simple recursive definition: if n = 0, return 1, else return n * f(n-1).
Cascade, 18 bytes
#1]*
\aa?
(\&;
a ?
Golfed version by Jo King.
A program without @ starts at the top-left corner. The main difference with my version is that a is decremented under the second branch, not first:
?
]
a ?
&;(
a
Cascade, 22 bytes
? @
]*#1
)(|a
a?\
&;a\
Solved as part of LYAL 2021-09-29.
How it works
Cascade programs start the execution at the entry point @.
? @ The main program prints (#) the result of the huge loop
# starting at `?`
|
\
\
? (grid rotated once for clarity)
] On entry, the if-clause is run:
a ( Push to the stack "a" the decrement of...
? If EOF, the top value of "a", otherwise the input from stdin
&;a
? If the above is not positive, return 1;
1 * Otherwise return (increment of a) times
) | the next invocation of the main loop
a \
\
Quipu, 41 bytes
1&1&1&0&
[]--[][]
**2&0&/\
1&>=>>
>>\/
1&
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
Scala 3, 79 bytes
import compiletime.ops.int._
type F[N<:Int]=N match{case 0=>1 case _=>N*F[N-1]}
Quipu, 64 bytes
\/1&1&0&2&
3&++[][][]
>>3&**1&/\
1&[]1&++
;;%%>>1&
3&4&1&??
??==
I decided to try out Quipu for LYAL event, and it's pretty fun to finagle with. I originally had this answer on the other factorial question, not realizing that it was invalid due to overflow.
Ungolfed:
"0 1 2 3 4
---------------"
\/ 1& 1& 0& 2&
3& ++ [] [] []
>> 3& ** 1& /\
1& [] 1& ++
;; %% >> 1&
3& 4& 1& ??
?? ==
Thread 0 takes input, then jumps to thread 3 if N > 0, otherwise it sets its value to 1 and jumps to thread 3.
Thread 3 then takes the value of thread 0 (N if N > 0, else 1) and increments it by 1 (we'll call this M), then jumps to thread 1.
Thread 1 increments its value, which acts as the accumulator (acc), and if acc == M, it jumps to thread 4, otherwise it jumps to thread 2.
Thread 2 takes its value (X) and multiplies it by acc. If X != 0, it jumps back to thread 1, otherwise it sets X to 1 and jumps to thread 3.
Once acc reaches M, execution jumps to thread 4, which prints the value of thread 2.
jq, 30 bytes
reduce(range(.)+1)as$i(1;.*$i)
My first jq answer.
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;
A recursive function. reduce is a shorthand for a function like this.
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)
PPL, 60 bytes
fnf(n){
declarea=1
declares=1
loopn{
a=a*s
s=s+1
}
returna
}
Anybody remember PPL? ;)
Declares a new function f with variables a and s. Loops n times and multiplies a by s each time.
Sadly recursion is not supported with PPL.
Python 3, 61 50 48 bytes
a=1
for i in range(int(input())):a*=i+1
print(a)
Thanks to Bubbler for shortening the code by 11 bytes. Another thanks to Jo King♦ for shortening the code by 2 bytes.
Vyxal, 1 byte
¡
Built-in factorial.
No built-in, 2 bytes
ɾΠ
Explanation:
# Implicit input
ɾ # Range [1, N]
Π # Reduce by multiplication
# Implicit output
Pinecone, 45 bytes
f::{Int}:(k:1;i:1|i<=in|i:i+1@k:k*i;print:k)
Factor + math.factorials, 6 bytes
[ n! ]
Thanks to @Bubbler for -9 bytes
Factor + math.factorials, 15 bytes
[ factorial . ]
Pxem, 26 bytes (filename) + 0 bytes (content) = 26 bytes.
- Filename (escaped):
\001._.c.w.t.m.!.m\001.-.c.a.s.n - Content: empty
Usage
- Input decimal integer from STDIN
- Output to STDOUT
How it works
XX.z
.a\001XX.z # push one
.a._.c.wXX.z # push getint; dup; while pop!=0; do
.a.t.m.!XX.z # heap=pop; push heap; push pop*pop
.a.m\001.-XX.z # push heap; push 1; push abs(pop-pop)
.a.cXX.z # dup
.a.a.s.nXX.z # done; pop; printf "%d" pop
.a
PowerShell Core, 37 32 bytes
param($a)1..($a+!$a)-join'*'|iex
Or recursive:
PowerShell Core, 37 36 bytes
filter f{if($_){$_*(--$_|f)}else{1}}
All bytes reductions thanks to mazzy :)
Phooey, 15 bytes
=>&.[@<*>-1]<$i
=>&.[@<*>-1]<$i # stack tape
= # (0) >a 0 acc = 1
> # (0) a >0 move left
&. # (0) a >n read int
[ ] # (0) a >n loop while n != 0
@ # n a >n push n
<*> # (0) a*n >n multiply acc by n (popping from stack)
-1 # (0) a*n >n-1 subtract 1 from n
< # (0) >res 0 go right to the result
$i # (0) >res 0 print as integer
Since Phooey uses int64_t, this supports up to 20.
Assembly (MIPS, SPIM), 78 bytes, 6*9 = 54 assembled bytes
main:li$2,5
syscall
li$4,1
f:beqz$2,g
mul$4,$4,$2
sub$2,1
b f
g:li$2,1
syscall
This is a significant optimization of this answer, but the account was deleted.
Specifically, this makes the following changes:
- It compares once at the top of the loop, using an unconditional branch at the bottom
- It uses the numerical register names which are shorter
- It removes spaces between mnemonics, as SPIM accepts this
- It removes the second operand from
sub
Otherwise, the logic is identical.
Whispers v3, 25 bytes
> Input
>> 1!
>> Output 2
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)!)
Javascript (ES6),19 bytes
f=n=>n?f(n-1)*n:1
BRASCA v0.4, 11 bytes
v0.4 was made after my initial solution and added the r operator, hence the seperate answer.
ig0$r[*$]xn
Explanation
ig - Convert to numbers and concatenate digits
0$r - Push range (i, 0) to stack
[*$] - Multiply it all
xn - Remove the 0 and output the result
BRASCA, 15 14 bytes
ig[:1-]x[*$]xn
Explanation
ig - Convert to numbers and concatenate
[:1-] - Generate a sequence from N to 0 on the stack
x - Remove the 0
[*$] - Multiply it all together
$n - Bring the number to the front and output it
ARM Thumb-2, 12 bytes
2101 b110 4341 3801 d1fc 4770
Commented assembly:
.syntax unified
.arch armv6t2
.thumb
.globl factorial
.thumb_func
// input: r0
// output: r1
factorial:
// accumulator starts at 1
movs r1, #1
// skip to end if r0 is zero
cbz r0, .Lend
.Lloop:
// r1 *= r0
muls r1, r0
// while (--r0)
subs r0, #1
bne .Lloop
.Lend:
// return
bx lr
Standard iterative approach.
Takes a 32-bit integer in r0, returns a 32-bit integer in r1.
ARM Thumb-2, 20 bytes
2201 2300 b128 fba2 2100 fb03 1300 3801 d1f9 4770
Commented assembly:
.globl factorial64
.thumb_func
// input: r0
// output: {r2, r3}
factorial64:
// accumulator starts at 1
movs r2, #1
movs r3, #0
// skip to end if r0 is zero
cbz r0, .Lend64
.Lloop64:
// {r2, r3} *= r0
// tmp = (u64)r2 * r0
umull r2, r1, r0, r2
// {r2, r3} = tmp + (r3 * r0 << 32)
mla r3, r3, r0, r1
// while (--r0)
subs r0, #1
bne .Lloop64
.Lend64:
// return
bx lr
This version uses 64-bit arithmetic, at the cost of 8 bytes. It is only 2 more instructions, but two of those instructions are now wide instructions. 😭
Takes a 32-bit integer in r0 and returns a 64-bit integer in {r2, r3} (easy to forward to printf)
Kotlin, 37 bytes
fun a(n:Int)=(1..n).fold(1){a,b->a*b}
Had to use fold(1){a,b->a*b}(surprisingly enough 1 less byte than something like fold(1,Int::times)) due to a lack of a product function in the stdlib.
convey, 16 bytes
}>-1
1@"v
^*",{
Loops over the input value until it reaches 0. There may be a shorter way using the indices command (/.), but it seems to take up more logic than I want. Since the interpreter includes a handy-dandy gif maker, you can even see it in action.
Labyrinth, 16 bytes
?+1#*
(: (;
@!;
Utilizes two loops, one to duplicate and decrement the input until zero, then one to multiply all the items on the stack.
ink, 50 bytes
==function f(n)
{
-!n:~return 1
}
~return n*f(n-1)
Had to make it a proper function instead of just a stitch, since I actually have to use the return value (so outputting by printing is not an option - or at least not a good one).
Flurry -nii, 14 bytes
{}{<({})[]>}{}
Takes single number from the stack and prints its factorial from the return value.
The online interpreter implements certain arithmetic shortcuts, so it computes and prints 125! in an instant.
How it works
Iterate through 1 to n using the stack height and multiply all of them to the starting value of 1.
// n is the only content of the stack at program start
// 1 is popped from empty stack
main = pop push-mul pop
= n push-mul 1
// height yields 1 to n, since it is called after a push
// <a b> = a * b (where a, b are Church numerals)
push-mul = \x. <(push x) height>
GolfScript, 9 bytes
1\~,{)*}/
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
C#, 42 bytes
Using the power of fresh and new C# 9 we can achieve a stunning 42 bytes!
int f(int n)=>n<2?1:n*f(n-1);return f(10);
for C# 8 and the online example we need to add 38 bytes for a total of 70 bytes
class P{static int Main(){int f(int n)=>n<2?1:n*f(n-1);return f(10);}}
Arn, 2 bytes
↓;
Unpacked: .fact. Passes STDIN (_) into the factorial function via the . infix
3 byte solution:
A→.
Unpacked: *\~
\ Fold with
* Multiplication
~ 1-range
_ Variable initialized to STDIN; implied
F#, 26 bytes, by Laikoni
fun x->List.fold(*)1[1..x]
F#, 35 bytes
let rec f=function|0->1|x->x*f(x-1)
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
Mini-Flak, 56 bytes
{(({}[()])({({}({}))[({}[({})()])]}{}{})[({})])}{}({}())
When golfing a fold operation in Brain-Flak, it is generally better to keep the stack small and use a "generator" than to push the entire list at once. I'm not exactly why this is true, but it typically works out that way. In this case, it avoids an entire swap operation, since the loop index can stay on top the whole time.
The other main optimization is to make the bottom of the stack equal the running total minus 1. This 1 has to be added back later, but this is shorter than pushing a 1 below the input at the beginning.
The multiplication algorithm here is a variant of the swap algorithm. Specifically, there are two equivalent swap algorithms: (({}({}))[({}[{}])]) calculates B as (A + B) - A, while (([{}]({}))([{}]{})) calculates B as (B - A) + A. To use this in a multiplication loop, we can modify these to not destroy B, and also decrement A by 1. There are three ways to add a single () to decrement A:
([{}]()({}))([{}]({}))evaluates toB.([{}]({}))([{}()]({}))evaluates toB - 1({}({}))[({}[({})()])]evaluates toB + 1
The latter is what we want, since B is one less than the factor I actually want to represent. By multiplying A - 1 by B + 1 and then adding B, we obtain A(B+1) - 1 as desired.
# Running counter: A
# Running product: B+1
# Start main loop
{
(
# Subtract 1 from A
({}[()])
# Multiply by B+1
({({}({}))[({}[({})()])]}
# Add B to get A(B+1) - 1 and push
{}{})
# Cancel out product to push A-1 again
[({})])
}{}
# Add 1 to get final result
({}())
x86-16 / x87 machine code, 13 bytes
Binary:
00000000: d9e8 e308 518b f4de 0c59 e2f8 c3 ....Q....Y...
Listing:
D9 E8 FLD1 ; start with 1
E3 08 JCXZ DONE ; if N = 0, return 1
FACT_LOOP:
51 PUSH CX ; push current N onto stack
8B F4 MOV SI, SP ; SI to top of stack for N
DE 0C FIMUL WORD PTR[SI] ; ST = ST * N
59 POP CX ; remove N from stack
E2 F8 LOOP FACT_LOOP ; decrement N, loop until N = 0
DONE:
C3 RET ; return to caller
Callable function. Input \$n\$ in CX, output \${n!}\$ in ST(0). Works for values of \$n\$ up to 21 (before loss of precision).
Or recursive...
x86-16 / x87 machine code, 15 bytes
D9 E8 FLD1 ; start with 1
FACT_CALL:
E8 0A JCXZ DONE ; if N = 0, end recursion
51 PUSH CX ; push current N onto stack
49 DEC CX ; decrement N
E8 F9FF CALL FACT_CALL ; recurse N-1
8B F4 MOV SI, SP ; SI to top of stack for N
DE 0C FIMUL WORD PTR[SI] ; ST = ST * N
59 POP CX ; remove N from stack
DONE:
C3 RET ; return from recursive call
Or x64 just for grins...
x86_64 machine code, 12 11 bytes
31: 6a 01 push 0x1 # start with 1
33: 58 pop rax
35: e3 05 jrcxz 3c <done> # if 0, return 1
0037 <f_loop>:
37: 48 f7 e1 mul rcx # rax = rax * N
3a: e2 fb loop 37 <f_loop> # loop until N = 0
003c <done>:
3c: c3 ret # return to caller
Input \$n\$ in rcx, output \${n!}\$ in rax for values of \$n\$ up to 20.
- -1 bytes thx to @PeterCordes on x86_64!
Python 2, 46 bytes
lambda n:reduce(lambda a,b:a*b,range(1,n+1),1)
How it works:
the reduce function takes in the list that contains all the numbers from 1 to n and reduces it by the multiplication function (lambda a,b:a*b) to a single number. An optional initial parameter is set in the case that n is equal to 0.
Shakespeare Programming Language, 106 bytes
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck]Ajax:Listen tothy!You is the factorial ofyou!Open heart
Uses the built-in the factorial of, which isn't described at all in the official docs.
Commented
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck] # header
Ajax:Listen tothy! # read (numeric) input
You is the factorial ofyou! # take factorial
Open heart # numeric output
Forth (gforth), 30 bytes
: f 1 swap 0 ?do i 1+ * loop ;
Code Explanation
: f \ start a new word definition
1 swap 0 \ create accumulator and set up loop parameters
?do \ start a conditional counted loop from 0 to n
i 1+ * \ multiply accumulator by loop index + 1
loop \ end counted loop
; \ end word definition
Scala 2.12, 14 bytes
1 to _ product
This is a function expression, where the underscore is the parameter. 1 to _ creates a range object, and product calculates the product of all numbers.
Pepe, 57 bytes
3 bytes have been decreased from my Pepe factorial program.
rrEEReREEEEErEeREeEreEREErEEEEErEEEeeReererRrEEEEEEeEreEE
Haskell, 17 bytes
f n=product[1..n]
- Thanks to 79037662 for suggesting it!
18 bytes
f 0=1
f x=x*f(x-1)
Or 19 bytes using fold.
f n=foldr(*)1[2..n]
Miniflak, 90 80 bytes
-10 bytes thanks to @Nitrodon!
{(({})[()])}{}((())){({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}
We already have another Brain-Flak answer here, but it uses both stacks and so doesn't work in Miniflak (a restricted subset of Brain-Flak where <, > and [] are disallowed). To avoid the second stack, this program uses a different multiplication algorithm.
Explanation
{(({})[()])}
{ } # While the top of the stack is nonzero:
{} # Pop the stack
( ) # Push a copy on the stack
[()] # Subtract 1
( ) # Push the result
This part counts down from the input value to 0, leaving a copy of each number in order.
{}((()))
{} # Pop the zero on the top
((())) # Push 1 twice
These extra ones are there so that when the input is 0 or 1, we multiply them together to get 1 instead of accidentally multiplying something by 0.
{({(()[{}]({}))([{}]({}))}({}{})[{}])(({}({}))[({}[{}])])}{}
{ } # While the top of the stack is nonzero:
({(()[{}]({}))([{}]({}))}({}{})[{}]) # Multiply the top two values
(({}({}))[({}[{}])]) # Swap the top two values
{} # Remove the zero on top
This loop is the core of the program: at each step, it multiplies the top two numbers together and then brings the number below them to the top. When we run out of numbers, a zero gets swapped to the top, and the loop ends. We then remove that zero, and the result of multiplying all the numbers together (which is the factorial of the input, as the numbers counted down from it to 1) is left.
How does this multiplication algorithm work?
(Suppose the top two numbers on the stack are a and b.)
({(()[{}]({}))([{}]({}))}({}{})[{}])
{} # Pop a
[ ] # Subtract it ...
() # ... from 1
({}) # Add b
( ) # Push the result
[{}] # Subtract that ...
({}) # ... from b ...
( ) # and push the result
{ } # Repeat until a reaches 0, keeping a running total of the sum of both results
{}{} # Pop a and b, add them together, ...
( )[{}] # ... and ignore the result
( ) # Push the running total
During each run-through, a (the top of the stack) is replaced by b-(b+(1-a)), which equals a-1. This repeats until a reaches 0, so the number of iterations is equal to the first input. The running total keeps track of the sum of the two results at each iteration. The first result is b+(1-a) and the second is a-1, so their sum is always b, the second input. This means that keeping track of the running total yields the product of the two inputs. Finally, before pushing the product, we pop a and b because we don't need them anymore.
The last piece is the swapping algorithm:
(({}({}))[({}[{}])])
{} # Pop the top number
({}) # Add the second number
( ) # Push the result
{} # Pop the sum
{} # Pop the second number ...
[ ] # ... and subtract it from the sum
( ) # Push the result (the first number) ...
[ ] # ... and subtract that from the previous result (the sum)
( ) # Push the final result (the second number)
Since the first number is pushed back before the second one, their order is swapped from before.
ArnoldC, 409 bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE f
YOU SET US UP 1
HEY CHRISTMAS TREE x
YOU SET US UP 0
GET YOUR ASS TO MARS x
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
STICK AROUND x
GET TO THE CHOPPER f
HERE IS MY INVITATION f
YOU'RE FIRED x
ENOUGH TALK
GET TO THE CHOPPER x
HERE IS MY INVITATION x
GET DOWN 1
ENOUGH TALK
CHILL
TALK TO THE HAND f
YOU HAVE BEEN TERMINATED
Iterative approach, it just loops starting from the input number and decreasing it until it reaches 0.
Rust, 27 bytes
Closure that takes n as its input. Thanks to madlaina
|n|(1..=n).fold(1,|f,x|f*x)
Sample wrapper program to call closure (111 bytes).
fn main(){let f=|n|(1..=n).fold(1,|f,x|f*x);print!("{}",f(std::env::args().nth(1).unwrap().parse().unwrap()));}
Rust, 104 bytes
fn main(){print!("{}",(1..=std::env::args().skip(1).next().unwrap().parse().unwrap()).fold(1,|f,x|f*x))}
Rust sure isn't built for golfing, but 'twas interesting to do so! Takes n via program arguments. Conveniently fails at 13!
I'm certain a fair number of bytes can be shaved from this, possibly if the unwrap() calls can be eliminated using ? and a Result.
COW, 150 bytes
oomMOOMOoMMMmoOmoOmoOMMMMMMMoOmOomOomOoMOOmoOMMMmoOmoOMMMOOOmOoMMMmOoMOOmoOMMMMOOmoOMoOmOoMOomooMMMmOoMOomoomOoMOoMMMmoomoOmoOmoOOOMOOOMOomOOmooMoOOOM
Commented
Four memory blocks are used. Block 1 stores a persistent counter. Blocks 2 and 3 store the temporary loop variables used for multiplication (by repeated addition). Block 4 stores the result.
oom # read input into Block 1
MOO # if input is not 0
MOoMMM # decrement and copy
moOmoOmoOMMMMMMMoOmOomOomOo # paste and increment to initialise Block 4
MOO # Loop 1: from Block 1 value down to 1
moOMMM # set Block 2 to Block 1 value
moOmoOMMMOOOmOoMMM # set Block 3 to Block 4 value and zero Block 4
mOoMOO # Loop 2: from Block 2 value down to 1
moOMMMMOO # Loop 3: as many times as Block 3 value
moOMoO # increment Block 4
mOoMOomooMMM # end Loop 3
mOoMOomoo # end Loop 2
mOoMOoMMMmoo # end Loop 1
moOmoOmoOOOM # print Block 4 value
OOOMOomOO # exit
moo # (only get here if input is 0)
MoOOOM # print 1
Muriel, 128 bytes
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";@"B:\".$(1\";a:"+~+";C:\""+|C+C
Moving another answer from the previous challenge, this time because the answer uses an eval function... in a language where that's the only way to loop.
This is a difficult for a number of reasons. First is Muriel itself, where the only way to do loops is to create a quine and eval it, passing a condition into the code. Next is that large numbers lose precision over time (so the output for \$125!\$ is 1.88267717688893e+209), but the program can't handle that format inside the program itself, so you can't pass large numbers to the next iteration of code. The last problem is that numbers will eventually be so large, the program just renders them as Inf, but thankfully that's far beyond \$125!\$, so we don't have to worry about that.
Explanation:
The first iteration doesn't have to be a complete quine, but can take shortcuts in constructing the actual loop.
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";
This creates an string version of the loop. This string persists across all iterations of the loop.
@ # Evaluate the next strings as a new program
"B:\".$(1\"; # Initialise B as the string ".$(1"
a:"+~ # Initialise a as the inputted number
+"C:\""+|C # Initialise C as the persistent string C
+C # And add the executing part of the program
The resulting program with input 125 looks like (newlines added for clarity)
B:".$(1";
a:125;
C:"\";@%(B+\");B:\\\"\"+B+\"*\"+$a+\"\\\";a:\"+$(a-1)+\";C:\\\"\"+|C+C),(a>0)*(&B+2),a*999+&B+2";
@%(B+");B:\""+B+"*"+$a+"\";a:"+$(a-1)+";C:\""+|C+C),(a>0)*(&B+2),a*999+&B+2
The eval then executes
@ # Evaluate
%( ... ),(a>0)*(&B+2),a*999+&B+2 # The substring
B+"); # If a is 0, evaluate B
# Otherwise
B:\""+B+"*"+$a+"\"; # Concatonate "*a" to the end of B
a:"+$(a-1)+"; # Decrement a
C:\""+|C # Set C to C
+C # And add the executing part of the program
Eventually, a will reach 0, and B will be evaluated. B will look like:
. # Print
$( ... ) # The string form of
1*125*124*123*...*1 # The factorial
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
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
PHP, 38 bytes
Recursive...
function f($n){return$n?$n*f($n-1):1;}
Or functional...
PHP, 39 bytes
fn($n)=>$n?array_product(range($n,1)):1
K (ngn/k), 6 bytes
Solution:
*/1+!:
Explanation:
*/1+!: / the solution
!: / range 0..N
1+ / add 1 (vectorised)
*/ / product
Extra:
- Also
*/-!-:for the same byte count.
cQuents, 5 bytes
$0:$!
The first three bytes are for 0-indexing, since by default cQuents uses 1-indexing.
Java, 37 36 bytes
int f(int n){return n<2?1:n*f(n-1);}
I simply wanted to try to participate although Java is not the best language to have as little bytes as possible.
This is simply the definition coined to Java, with a recursive call.
edit: one byte less, thx @Jo King
Lua, 36 bytes
x=1 for i=1,...do x=x*i end print(x)
On Lua <= 5.2 this will use double, allowing big inputs to work. On Lua 5.3+ (as currently on TIO) integers are used instead, making big inputs fail. This can be worked around at cost of one byte:
Lua, 37 bytes
x=1. for i=1,...do x=x*i end print(x)
ReRegex, 47 bytes
#import math
\b1!/1/(\d+)!/($1-1)!*$1/
#input
!
Defines two regexes;
(\d+)!/($1-1)!*$1/ Looks for a base10 number followed by a !, and replaces it with (n-1)!*n.
\b1!/1/ Replaces any free standing 1!'s with just 1.
The math library then takes care of the subtractions and multiplications. ReRegex will continue attempting its regex operations until it can no-longer modify the text.
The final two lines put the input as n! ready for the operations.
Values greater than 5 work offline, but due to how long they take; do not work on TIO.
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/
T-SQL, 91 bytes
CREATE FUNCTION dbo.f(@ INT)RETURNS INT AS BEGIN SET @=IIF(@<=1,1,@*dbo.f(@-1))RETURN @ END
It seems you need to specify a schema (dbo.) in order to make a recursive function :( Perhaps other SQL dialects are shorter.
Wolfram Language (Mathematica), 11 bytes
Gamma[#+1]&
Wolfram Language (Mathematica), 15 bytes
1~Pochhammer~#&
Wolfram Language (Mathematica), 19 bytes
If[#>0,#0[#-1]#,1]&
Wolfram Language (Mathematica), 24 bytes
The determinant of the n*n matrix of reciprocals of beta functions is n!
Det[1/Beta~Array~{#,#}]&
Wolfram Language (Mathematica), 26 bytes
GroupOrder@*SymmetricGroup
R, 15 bytes
gamma(scan()+1)
There is also factorial which appears to be allowable as a 9-byte solution.
MathGolf, 1 byte
!
Explanation:
! # Get the factorial (aka gamma(n+1)) of the (implicit) input-integer
# (output the entire stack joined together implicitly as result)
Befunge-93, 20 19 bytes
&+#v:!_:
\@#<*_\:.#
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:#*_$.@
CJam, 4 bytes
rim!
I'm sure there's other 4-bytes solutions, but I quite like how this makes an English word with punctuation, even if exclaiming "rim!" without context seems absurd.
Rattle, 23 20 bytes
|s>s[0+q][g-s<*~s>]~
This is the answer that I could not post on the other challenge! (see this)
Note that I do not have an online interpreter for Rattle yet so the interpreter is mashed together into the header on TIO (which is why TIO thinks it's Python 3 code but what's in the code section is only Rattle code - ignore the header and footer).
This actually works for up to 170! (but will a loss of precision, of course). In the next Rattle update this will actually become a builtin - making the possible solution just two bytes - but for its current version this is likely the shortest and most interesting factorial program.
Explanation
| takes user's input
s>s saves the input to memory slots 0 and 1
[0+q] if the top of the stack is equal to zero: increments, and quits (implicitly prints the top of the stack)
[ ]~ loop n times, where n is the value in storage at the pointer
g-s gets the value at the pointer, decrements, and saves
< moves pointer left
*~ pushes product of old top of stack and value at pointer to new top of stack
s saves to memory slot at pointer
> moves pointer right
(implicitly outputs the value at the top of the stack after the program executes)
In essence, this program saves the given value (from input) to two memory slots. Then, it decrements one memory slot and multiplies the other by the decremented value, until the value decrements to 1, then it outputs the final value.
Charcoal, 8 bytes
IΠ…·¹∨N¹
Try it online! Link is to verbose version of code. Explanation:
N `n` as a number
∨ Logical Or
¹ Literal `1`
…·¹ Inclusive range from `1` to `n`
Π Take the product
I Cast to string
Implicitly print
TI-BASIC (TI-83), 2 bytes
Ans!
Takes input via Ans. The character count differs from the byte count because TI-BASIC is tokenised; Ans and ! are both 1-byte tokens.
Sample output
Uses this emulator.
brainfuck, 56 bytes
+>,[[>+>+<<-]>[-<<[->+<<+>]<[->+<]>>>]<<[-]>[->+<]>>-]<.
Takes input and outputs as byte values. Since this interpreter has 8 bit size cells, it can't really do anything larger than 5!. You can use this interpreter to try larger values.
Brain-Flak, 52 bytes
<>(())<>{(({}[()]))({<>({})<><({}[()])>}{}<>{})<>}<>
Posting my own Brain-Flak solution, which differs from the same size one from the older challenge.
Zephyr, 72 bytes
input n as Integer
set f to 1
for i from 1to n
set f to f*i
next
print f
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.
QBasic, 37 bytes
INPUT n
f=1
FOR i=1TO n
f=f*i
NEXT
?f
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.
The values here are single-precision by default, which means that after 10! we start getting output in scientific notation. The values are still accurate for 11! and 12!, though (e.g. 12! gives 4.790016E+08). At 13! we start to see rounding error (6.227021E+09 for 6227020800). If we use a double-precision variable f# in place of f (+4 bytes), we get accurate results up to 21!.
C (gcc), 21 bytes
Uses the assignment trick, works consistently in GCC without optimizations.
O(o){o=o?o*O(~-o):1;}
Google Sheets / Excel / Numbers, 8 bytes
=FACT(A1
All three spreadsheet programs close parentheses automatically.
Retina, 29 bytes
.+
*
.
$.<'$*
~`.+
.+¶$$.($&_
Try it online! Explanation:
.+
*
Convert n to unary.
.
$.<'$*
Count down from n in decimal, with trailing *s.
~`.+
.+¶$$.($&_
Wrap the result in a Retina replacement stage and evaluate it.
Example: For n=10, the resulting stage is as follows:
.+
$.(10*9*8*7*6*5*4*3*2*1*_
This calculates the length of the string obtained by repeating the _ by each of the numbers from 1 to 10.
Explanation for n=0:
.+
*
Delete the input.
.
$.<'$*
Do nothing.
~`.+
.+¶$$.($&_
Do nothing, and evaluate the resulting empty stage on the empty string.
The empty stage returns 1 more than the character count. As the string is empty, this is just 1. Conveniently, this is the result we wanted all along.
It is of course possible to calculate the factorial properly even for n=0, but my best attempt took 30 bytes.
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
SNOBOL4 (CSNOBOL4), 65 bytes
i =input
p =1
i x =x + 1
p =p * x
output =p le(i,x) :f(i)
end



