title: Is this number a factorial?

text:
# Question
Title: Is this number a factorial?
# The Task

Given a natural number as input, your task is to output a truthy or falsey value based on whether the input is a factorial of any natural number. You can assume that the input number will always be in the range of numbers supported by your language, but you must not abuse native number types to trivialize the problem.

Standard Loopholes apply.

---

## Input

You'll be given a natural number (of type `Integer` or similar).

You can take input in any way you want except assuming it to be in a predefined variable. Reading from file, console, dialog box (`prompt`), input box etc. is allowed. Input as function argument is allowed as well!

---

## Output

Your program should output a truthy or falsey value based on whether the input number is a factorial of any natural number.

Make sure that your truthy/falsey values are consistent for all inputs, i.e, if you are using pair of 1 and 0 to denote truthy and falsey values respectively, then your program must output 1 for all inputs that should have truthy values and 0 for all inputs that should have falsey values.

You can take output in any way you want except writing it to a variable. Writing to file, console, screen etc. is allowed. Function `return` is allowed as well!

Your program must not produce errors for any input!

---

## Test Cases

```
Input     Output

1         Truthy (0! or 1!)
2         Truthy (2!)
3         Falsey
4         Falsey
5         Falsey
6         Truthy (3!)
7         Falsey
8         Falsey
24        Truthy (4!)
120       Truthy (5!)

```

---

## Winning Criterion

This is , so the shortest code in bytes wins!

# Answer
> 41 votes
# Brachylog, 1 byte

Try it online!

### Explanation

is a built-in that asserts the following relation: its output is the factorial of its input. We simply give it a set output and see whether it suceeds or not with a variable input.

# Answer
> 31 votes
# ECMAScript Regex, ~~733~~ ~~690~~ ~~158~~ ~~119~~ ~~118~~ 92 bytes

* *dropped 1 byte (119 → 118) using a trick found by Grimmy that can futher shorten division in the case that the quotient is guaranteed to be greater than or equal to the divisor*
* *dropped 26 bytes (118 ~~(117)~~ → 92) thanks to Grimmy in collaboration with H.PWiz. I've finally analyzed, commented, and proved this version.*

My interest in regex has been sparked with renewed vigor after over 4½ years of inactivity. As such, I went in search of more natural number sets and functions to match with unary ECMAScript regexes, resumed improving my regex engine, and started brushing up on PCRE as well.

I'm fascinated by the alienness of constructing mathematical functions in ECMAScript regex. Problems must be approached from an entirely different perspective, and until the arrival of a key insight, it's unknown whether they're solvable at all. It forces casting a much wider net in finding which mathematical properties might be able to be used to make a particular problem solvable.

Matching factorial numbers was a problem I didn't even consider tackling in 2014 – or if I did, only momentarily, dismissing it as too unlikely to be possible. But last month, I realized that it could be done.

As with my other ECMA regex posts, I'll give a **warning:** I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. See this earlier post for a list of consecutively spoiler-tagged recommended problems to solve one by one.

So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above.

This was my idea:

> The problem with matching this number set, as with most others, is that in ECMA it's usually not possible to keep track of two changing numbers in a loop. Sometimes they can be multiplexed (e.g. powers of the same base can be added together unambiguously), but it depends on their properties. So I couldn't just start with the input number, and divide it by an incrementally increasing dividend until reaching 1 (or so I thought, at least).
> Then I did some research on the multiplicities of prime factors in factorial numbers, and learned that there's a formula for this – and it's one that I could probably implement in an ECMA regex!

After stewing on it for a while, and constructing some other regexes in the meantime, I took up the task of writing the factorial regex. It took a number of hours, but ended up working nicely. As an added bonus, the algorithm could return the inverse factorial as a match. There was no avoiding it, even; by the very nature of how it must be implemented in ECMA, it's necessary to take a guess as to what the inverse factorial is before doing anything else.

The downside was that this algorithm made for a very long regex... but I was pleased that it ended up requiring a technique used in my 651 byte multiplication regex (the one that ended up being obsolete, because a different method made for a 50 byte regex). I had been hoping a problem would pop up that required this trick: Operating on two numbers, which are both powers of the same base, in a loop, by adding them together unambiguously and separating them at each iteration.

But because of the difficulty and length of this algorithm, I used molecular lookaheads (of the form `(?*...)`) to implement it. That is a feature not in ECMAScript or any other mainstream regex engine, but one that I had implemented in my engine. Without any captures inside a molecular lookahead, it's functionally equivalent to an atomic lookahead, but with captures it can be very powerful. The engine will backtrack into the lookahead, and this can be used to conjecture a value which cycles through all possibilities (for later testing) without consuming characters of the input. Using them can make for a much cleaner implementation. (Variable-length lookbehind is for most uses at least equal in power to molecular lookahead, but the latter tends to make for more straightforward and elegant implementations. Molecular lookahead may also be able to do things in loops that aren't possible with variable-length lookebehind.)

So the 733 and 690 byte lengths do not actually represent ECMAScript-compatible incarnations of the solution – hence the "⚛" after them; it's surely possible to port that algorithm to pure ECMAScript (which would increase its length quite a bit) but I didn't get around to it... because I thought of a much simpler and more compact algorithm! One that could easily be implemented without molecular lookaheads. It's also significantly faster.

This new one, like the previous, must take a guess at the inverse factorial M, cycling through all possibilities and testing them for a match. It divides N by 2 to make room for the work it needs to do, and then seeds a loop in which it will repeatedly divide the input by a divisor that starts at 3 and increments up to M-1.\* (As such, 1! and 2! can't be matched by the main algorithm, and must be dealt with separately.) The divisor is kept track of by adding it to the running quotient; these two numbers can be unambiguously separated because, assuming M! == N, the running quotient will continue to be divisible by M until it equals M.

\*But it later turned out that starting the divisor at M-1, and decrementing down to 3, can result in a shorter regex. This was part of golfing 118 → 92 bytes.

> This regex does division-by-a-variable in the innermost portion of the loop. The division algorithm is the same as in my other regexes (and similar to the multiplication algorithm): for A≤B, A\*B=C if any only if C%A=0 and B is the largest number which satisfies B≤C and C%B=0 and (C-B-(A-1))%(B-1)=0, where C is the dividend, A is the divisor, and B is the quotient. (A similar algorithm can be used for the case that A≥B, and if it is not known how A compares to B, one extra divisibility test is all that is needed.)

So I love that the problem was able to be reduced to even less complexity than my golf-optimized Fibonacci regex, but I do sigh with disappointment that my multiplexing-powers-of-the-same-base technique will have to wait for another problem that actually requires it, because this one doesn't. It's the story of my 651 byte multiplication algorithm being supplanted by a 50 byte one, all over again!

With no further ado, here's the regex:

True/false version (**92 bytes**):

`^(((x+)\3+)(?=\3\3\2$)(x(?=\3+(x*))(?=\5+$)(?=((x+)(?=\5\7*$)x)\6*$)\3+(?=\5\7$))*\3xx|x?)x$`

Try it online!

Return inverse factorial or no-match (109 bytes):

`^(?=((x(x*))\2+)(?=\2\2\1$)(x(?=\2+(x*))(?=\5+$)(?=((x+)(?=\5\7*$)x)\6*$)\2+(?=\5\7$))*\2xxx$)(\3|xx)?x|^xx?$` (relies on ECMAScript no-empty-optional behavior)

Try it online!

Return inverse factorial or no-match, in ECMAScript + `\K` (103 bytes):

`^(((x(x*))\3+)(?=\3\3\2$)(x(?=\3+(x*))(?=\6+$)(?=((x+)(?=\6\8*$)x)\7*$)\3+(?=\6\8$))*x\Kxx(\K\4)?|x?)x$` (relies on ECMAScript no-empty-optional behavior)

Return inverse factorial or no-match, in ECMAScript + `(?*)` (103 bytes):

When adapted to molecular lookahead, this regex can match \\$3!\\$ in a straightforward way:
`^(?=(?*(x+))(\1*)(?=\1\1\2$)(x(?=\1+(x*))(?=\4+$)(?=((x+)(?=\4\6*$)x)\5*$)\1+(?=\4\6$))*\1xxx$)\1|^xx?$`

Return inverse factorial or no-match, in ECMAScript + `(?*)` \+ `\K` (**99 bytes**):

`^(?*(x+))(\1*)(?=\1\1\2$)(x(?=\1+(x*))(?=\4+$)(?=((x+)(?=\4\6*$)x)\5*$)\1+(?=\4\6$))*xxx\K\1$|^xx?$`

And the free-spaced version with comments:

```
# Match factorial numbers in the domain ^x*$
^                           # N = tail = input
(
    ((x+)\3+)(?=\3\3\2$)    # \3 = conjectured inverse factorial of N if N >= 4! = 24;
                            # \2 = N/2 - \3; assert tail is divisible by \3 and by 2;
                            # assert tail is divisible by a number >= 6;
                            # tail = N/2 + \3;
                            # Note that if N = 3! = 6, \3 will behave differently,
                            # because sticking to the pattern, we'd need \2=0, which
                            # is of course impossible, because we must have \2 >= \3.
                            # However, when N=6, \3=1 happens to result in a match after
                            # zero loop iterations.
    # The loop is seeded: X = N/2; I = \3 - 1; tail = X + I + 1
    # The loop will divide X by the numbers in the range \3-1 downward to 3, inclusive.
    # Since we don't divide by \3 itself, and already divided by 2, if N is factorial,
    # the end result of these divisions will be X = \3.
    (                       # Main loop
        x                   # tail = tail-1 = X + I
        (?=\3+(x*))         # \5 = tail % \3 = I; assert X >= \3
        (?=\5+$)            # assert X is divisible by I; if \3=1, then \5=0,
                            # and the main loop will exit after zero iterations
        (?=
            (               # \6 = tail / \5 = (X+I)/I = X/I + 1
                (x+)        # \7 = \6-1 = X/I; assert X/I >= 1
                (?=\5\7*$)
                x
            )
            \6*$
        )
        \3+(?=\5\7$)        # Prepare the next iteration of the loop: X = \7; I -= 1;
                            # tail = X + I + 1;
                            # Assert that the tail difference is divisible by \3, i.e.
                            # that, with our previous values of X and I:
                            #      X + I - (X/I + I-1 + 1)
                            #    = X/I*(I-1) is divisible by \3
                            # Since I is coprime with I-1, if X was divisible by \3
                            # but X/I is not, then X/I*(I-1) will not be either, so this
                            # indirectly asserts that X/I, our new X, is divisible by \3.
                            # The initial value of X was asserted to be divisible by \3
                            # before the loop started, so by induction, every new value
                            # of X will be asserted to be divisible by \3. This is
                            # important because we use modulo by \3 to recover the value
                            # of I at the beginning of each loop iteration.
                            # And if N = \3! and the previous of I=2 and X was able to be
                            # divided by 2, this will force this iteration of the loop to
                            # fail, and the loop will exit with the values of X and I
                            # backtracked to their values before this iteration, i.e.
                            # with X = \3 and I = 2.
    )*
    \3xx                    # assert tail = \3 + 2 + 1, meaning when the loop finished
                            # we ended up with X = \3 and I = 2
|
    x?                      # match N=1 and N=2, which the main algorithm can't
)
x$

```

The full history of my golf optimizations of these regexes is on github:

regex for matching factorial numbers - multiplicity-comparing method, with molecular lookahead.txt
regex for matching factorial numbers.txt (the one shown above)

## Optimized for returning the inverse factorial

The above algorithm has the quirk of happening to match \\$3!\\$ by coincidence, yielding a false inverse factorial value of \\$1\\$ instead of \\$3\\$. This complicates turning the regex into one that returns the inverse factorial as a match.

The below algorithm is cleaner in that it straightforwardly matches \\$3!\\$ with the correct inverse factorial value. It does however result in a longer true/false regex.

True/false version – returns inverse factorial minus 1 in `\1` (**96 bytes**):

`^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x+))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*\1x?$`

Try it online! \- true/false
Try it online! \- return value in `\1`

Return inverse factorial or no-match (**103 bytes**):

`^(?=(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x*))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*\1x?$)x\1`

Try it online!

Return inverse factorial in `\1` or no-match, in ECMAScript + `(?*)` (**97 bytes**):

`^(?*(x(x*))\1*$)\2((?=\1*(x*)(?=\1)\4(x*))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\1*(?=x\4\6$)\2)*\2x?$`

Return inverse factorial or no-match, in ECMAScript + `\K` (**101 bytes**):

`^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x(x*)))(?=\5+$)(?=((x*)(?=\5\8*$)x)\7*$)\2*\4(?=x\7$)\K\6)*\1x?$`

Return inverse factorial minus 1 or no-match, in ECMAScript + `\K` (**98 bytes**):

`^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x+))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*x?\K\1$`

```
# Match factorial numbers in the domain ^x*$ and return the inverse factorial as the match
^                           # N = tail = input
(?=
    (x*)                    # \1 = conjectured inverse factorial - 1; tail -= \1
    (?=x(x\1)*$)            # \2 = conjectured inverse factorial; assert \2 divides N;
                            #      assert N >= 2 * \2;
                            # If N=1 or N=2, then \2 will be unset (having experienced 0
                            # iterations of its mini-loop) and \1=0 or \1=1, respectively
    # The loop is seeded: X = N; I = \1; tail = X - I
    # The loop will divide X by the numbers in the range \2-1 downward to 2, inclusive.
    # We don't divide by \2 itself, so if N is factorial, the end result of these
    # divisions will be X = \2 - 1.
    (
        (?=
            \2*(x*)(?=\2)   # \4 = tail % \2 = \2-I; assert tail >= \2
            \4(x*)          # \5 = \2-\4 = I
        )
        (?=\5+$)            # assert X is divisible by I
        (?=
            (               # \6 = tail / \5 = (X-I)/I = X/I - 1
                (x*)        # \7 = \6-1
                (?=\5\7*$)
                x
            )
            \6*$
        )
        \2*(?=x\4\6$)\1     # Prepare next iteration of loop: X = \6+1; I -= 1;
                            # tail = X - I;
                            # Assert that, with our previous values of X and I:
                            #      (X - I) - (1 + \2-I + X/I - 1)
                            #    = X - \2 - X/I                   is divisible by \2
                            # Assuming X was already divisible by \2, this asserts
                            # X/I is also divisible by \2. The initial value of X was
                            # asserted to be divisible by \2, so by induction, every
                            # new value of X will be asserted to be divisible by \2.
                            # This is important because we use modulo by \2 to recover
                            # the value of I at the beginning of each loop iteration.
                            # And if I = 1, this iteration of the loop will fail
                            # because in this case,
                            #      1 + \4 + \6 > tail
                            #      \2-I + X/I > X - I
                            #      \2 > 0
                            # and the loop will exit with I = 1.
                            # But note that if N = \2!, then when we reach I = 1, and
                            # thus have X = \2 and tail = \2 - 1, this iteration of the
                            # loop will have already failed at its beginning due to the
                            # assertion that tail >= \2.
    )*
    \1x?$                   # assert tail = \1 = \2-1, meaning when the loop finished we
                            # ended up with X = \2 and I = 1,
                            # or tail = \1+1 (what would be \2), which can only happen if
                            # \2 is unset and N=1 or N=2 and the loop did 0 iterations.
)
x\1                         # return \1 + 1 as a match; don't use \2 because it will be
                            # unset in the case of N=1 or N=2

```

# Answer
> 21 votes
# Jelly, 4 bytes

```
Œ?IE

```

Not the shortest Jelly answer, but it's rather efficient.

Try it online!

### How it works

```
Œ?IE  Main link. Argument: n

Œ?    Yield the n-th permutation of the positive integers, without the sorted tail.
      For 120, this yields [5, 4, 3, 2, 1], the tail being [6, 7, 8, ...].
  I   Increments; compute all forward differences.
      For 120, this yields [-1, -1, -1, -1].
   E  Check if all differences are equal.

```

# Answer
> 19 votes
# Jelly, 3 bytes

```
!€ċ

```

Try it online!

1 for yes, 0 for no.

## How it works

```
!€ċ  argument as z
!€   [1!, 2!, 3!, ..., z!]
  ċ  count the number of occurrence of z

```

# Answer
> 15 votes
## JavaScript (ES6), ~~30~~ ~~29~~ 28 bytes

Expects a positive integer. Returns `-1` for falsy and `-2` for truthy.

```
f=(n,k=2)=>n>1?f(n/k,k+1):~n

console.log(1,  '-->',f(1))   // Truthy (0! or 1!)
console.log(2,  '-->',f(2))   // Truthy (2!)
console.log(3,  '-->',f(3))   // Falsey
console.log(4,  '-->',f(4))   // Falsey
console.log(5,  '-->',f(5))   // Falsey
console.log(6,  '-->',f(6))   // Truthy (3!)
console.log(7,  '-->',f(7))   // Falsey
console.log(8,  '-->',f(8))   // Falsey
console.log(24, '-->',f(24))  // Truthy (4!)
console.log(120,'-->',f(120)) // Truthy (5!)
```

**Note**: This function supports pretty large inputs (you should read this as: 'pretty large for JS'). It should work safely up to *253 \- 1*. It will fail for sure starting at *N = 121,645,100,408,831,992*, this input being rounded to *19! = 121,645,100,408,832,000* because of its IEEE-754 encoding. There *may* be other false positive results before *121,645,100,408,831,991* because of rounding errors, but I don't know for sure.

# Answer
> 11 votes
# Python 3, ~~39~~ 38 bytes

```
f=lambda n,i=1:n>1and f(n/i,i+1)or n<1

```

A recursive function taking an integer, `n`, returning a boolean value inversley representing the result (truthy: `False`, falsey: `True`)

**Try it online!**

Repeatedly divides `n` by `i`, with an initial value of `1`, until the remainder is less than or equal to `1` then tests if that remainder is less then `1`, only factorials will end with a remainder equal to `1`, and `<` is a byte shorter than `==`.

# Answer
> 11 votes
# Java 8, 46 bytes

```
i->{int j=1,c=0;for(;j<i;j*=++c);return j==i;}

```

This is based on Roman Gräf's entry that I was able to knock a dozen or so bytes off of. I would have suggested it there but I don't have enough reputation to comment yet! My modified test runner code:

```
import java.util.function.Function;
import java.util.stream.IntStream;

public class IsFactorial {
    public static Function<Integer, Boolean> isFactorial = i->{int j=1,c=0;for(;j<i;j*=++c);return j==i;};
    public static int[] truthyCases = {1,2,6,24,120};
    public static int[] falsyCases = {3,4,5,7,8};
    public static void main(String[] args){
        System.out.println(
            IntStream.of(truthyCases).allMatch(i->isFactorial.apply(i)) &&
            IntStream.of(falsyCases).allMatch(i->!isFactorial.apply(i)));
    }
}

```

# Answer
> 10 votes
# Retina, ~~50~~ 38 bytes

*12 bytes saved thanks to @Neil by combining shortening the loop and by getting rid of the `;`*

```
.+
1¶$&$*
+`^(1+)¶(\1)+$
1$1¶$#2$*
¶.$

```

Try it online!

Outputs `1` for true and `0` for false.

`.+` matches the entire number

`1¶$&$*` replacing it with `1` followed by a newline and the match converted to unary

The remaining program divides the unary number in the bottom line by successively increasing positive integers, kept track in the top line, while it is possible to do so.

`+`` loop until string remains same

* `^(1+)¶(\1)+$` match the top line many `1`s and a multiple of it many `1`s on the bottom line and replace it with
* `1$1¶$#2$*` the top line many `1`s with another `1`, that is, increasing the number represented by the top line by 1, followed by the newline and the number of matches of the top line in the bottom line (ie. count of matches of the second capturing group) many `1`s, that is, dividing the bottom number by the top number

Once it is no longer possible to do so,

`¶.$` give the number of matches of this regex, ie. does there exist a lone `1` on the bottom line, which only happens if the number is a factorial

---

If no-crash/crash is allowed instead of truthy/falsy values, then I can get ~~36~~ 34 bytes.

```
^
1¶
{`.+$
$*
^(1+)¶(\1)+$
1$1¶$#2

```

This goes by the same approach, but combines the `$*` into the third and fourth lines. The third line onward is a part of the same loop, `{` is short for `+(` where the `(` groups the remaining lines into the loop. Factorials end in the program breaking out of the loop, while non-factorials get stuck in the loop forever until Retina throws an OverflowException caused by the last replacement failing thus having the bottom in unary instead of in decimal, and the first replacement of the loop converts the bottom line from decimal to unary, so it blows up quickly.

# Answer
> 9 votes
# C++, ~~102~~ ~~100~~ 92 Bytes

```
#include<cmath>
int a(int n){int i=n,j=0;for(;i;)j|=lround(exp(lgamma(i--+1)))==n;return j;}

```

Loops through all the values from `0` to `n` and calculates the factorial and then checks if it's equal to `n`.

Thanks Christoph! (saved 8 bytes)

# Answer
> 8 votes
# 05AB1E, 4 bytes

```
L!QO

```

Try it online!

**Explanation**

```
L      # range [1 ... input]
 !     # calculate factorial of each
  Q    # compare with input for equality
   O   # sum

```

# Answer
> 7 votes
# Haskell, ~~43~~ 26 bytes

```
f n=elem n$scanl1(*)[1..n]

```

Try it online!

* Saved 17 bytes, thanks to Laikoni

# Answer
> 6 votes
# Haskell, 38 bytes

```
m#n=n<2||mod n m<1&&(m+1)#div n m
(2#)

```

Try it online! Example usage: `(2#) 24`. Returns `True` or `False`.

This is the shortest I could get while still being very efficient. Even for numbers as large as

```
145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000

```

the result is immediately given. The solution works by dividing the input `n` by `m = 2,3,4,5,...` until either the result is one or `n` is not divisible by `m`.

For the shorter but incredible inefficient 26-byte solution which computes `n!` for inputs that are not factorials look here.

# Answer
> 5 votes
# Fourier, ~~40~~ 39 bytes

```
I~Q1~N(i^~i*N~N{Q}{1~Xo}N>Q{1}{1~X0o}X)

```

**Try it on FourIDE!**

Basically multiplies the number N by an increasing amount until N is either equal to (output 1) or greater than (output 0) the input.

***Explanation Pseudocode:***

```
Q = Input
N = 1
While X != 1
    i += 1
    N = N*i
    If N = Q Then
        Print 1
        X = 1
    End If
    If N > Q Then
        Print 0
        X = 1
    End If
End While

```

# Answer
> 5 votes
# Japt, ~~8~~ 6 bytes

```
ol x¥U

```

Try it online!

This outputs 0 for false and 1 for true.

# Explanation

```
 ol x¥ U
Uol x==U
Uo       # Create the range [0 ... input]
  l      # Replace each element by its factorial
     ==U # Compare each element to the input (yielding 1 if equal and 0 otherwise)
    x    # And sum the result

```

# Answer
> 5 votes
# MATL, 5 bytes

```
t:Ypm

```

Try it online!

### Explanation

```
t     % Implicit input. Duplicate
:     % Range from 1 to that
Yp    % Cumulative product
m     % Ismember. Implicit display

```

# Answer
> 5 votes
# APL (Dyalog Unicode), 5 ~~6~~ ~~7~~ bytes

*Golfed a byte by changing `×/` to `!` thanks to Erik the Outgolfer*

```
⊢∊!∘⍳

```

Try it online!

### Explanation

```
    ⍳                      Range of numbers from 1 to argument, 1 2 3 4 .. n
   !                       Factorial; 1! 2! 3! 4! .. n!
⊢∊                         Is the right argument a member of this list?

```

# Answer
> 5 votes
# C++ (clang), ~~51~~ 47 bytes

*-4 bytes thanks to Grimmy*

Recursion wins out as far as golfing goes.

**47 bytes**, with floating point and a global variable:

`int i;int f(double n){return n>1?f(n/++i):i=n;}`

Try it online!

`double` is used instead of `float` because otherwise it'd start giving false positives around 11! (everything from 39916798 to 39916802 would be identified as factorial).

This takes advantage of global variables being initialized (in the case of the integer `i`, to zero).

`i=n` casts a `double` floating point value to `int`. Any `n<1` will be rounded down to `0` (falsey). A value of `1` (truthy) will result if and only if `n==1` exactly.

The function cleans up after its change to the global variable upon finishing its recursion, by setting it to `0` or `1` with `i=n`. Which of those it is makes no difference; an value of `1` will merely result in the initial division by `1` being skipped the next time the function is invoked.

**49 bytes**, with floating point:

`int f(double n,int i=2){return n>1?f(n/i,i+1):n;}`

Try it online!

---

**51 bytes**, zero is true:

`int f(int n,int i=2){return n<2?!n:n%i|f(n/i,i+1);}`

This sacrifices quite a lot of speed for 1 byte of savings. Replace the `|` with `||` to make it fast, due to short-circuit evaluation of the logical OR.

Try it online! (51 byte slow version)
Try it online! (52 byte fast version)

Ungolfed slow version:

```
int isFactorial(int n, int i=2)
// returns 0 for true, and nonzero for false
{
    if (n < 2) // same as "if (n==0 || n==1)" in our natural number input domain
    {
        if (n==0)
            return 1; // not factorial
        else // n==1
            return 0; // is factorial (could be either 0! or 1!)
    }

    // Because any nonzero value represents "false", using "|" here is equivalent
    // to "||", provided that the chain of recursion always eventually ends. And
    // it does always end, because whether or not "n" is factorial, the "n / i"
    // repeated division will eventually give the value of zero or one, satisfying
    // the above condition of termination.
    return (n % i) | isFactorial(n / i, i+1);
}

```

Ungolfed fast version:

```
int isFactorial(int n, int i=2)
// returns 0 for true, and nonzero for false
{
    if (n < 2) // same as "if (n==0 || n==1)" in our natural number input domain
    {
        if (n==0)
            return 1; // not factorial
        else // n==1
            return 0; // is factorial (could be either 0! or 1!)
    }

    if (n % i != 0)
        return 1; // not factorial
    else
        return isFactorial(n / i, i+1);
}

```

There are many ways to rearrange this.

**52 bytes**, nonzero is true:

`int f(int n,int i=2){return n<2?n:n%i?0:f(n/i,i+1);}`

Try it online!

**52 bytes**, zero is true:

`int f(int n,int i=2){return!n?1:n%i?n-1:f(n/i,i+1);}`

Try it online!

---

Before resorting to recursion, I tried making some iterative versions, and they came close.

**54 bytes**, nonzero is true:

`int f(int n){for(int i=2;n>1;)n=n%i?0:n/i++;return n;}`

Try it online!

**54 bytes**, zero is true (based on Roman Gräf's Java 8 submission):

`int f(int n){int a=1,i=0;for(;a<n;a*=++i);return a-n;}`

Try it online!

But as Grimmy pointed out, with floating point it can be shorter, even when done iteratively...
**50 bytes**, nonzero is true, floating point:

`int f(double n){for(int i=2;n>1;)n/=i++;return n;}`

Try it online!

---

Now, for the bottom of the barrel, recursive versions with no `n==0` handling (I consider these invalid, because 0 is a natural number, and any definition in which it is not makes for "natural numbers" of very limited use). In the below versions, the infinite recursion of `f(0)` either triggers a segfault due to overflowing the stack, or with compilers that optimize it to iteration, loops endlessly:

**48 bytes**, zero is true:

`int f(int n,int i=2){return n%i?n-1:f(n/i,i+1);}`

Try it online!

**48 bytes**, zero is true (based on Hagen von Eitzen's 33 byte C (gcc) submission):

`int f(int n,int e=0){return n%++e?n-1:f(n/e,e);}`

Try it online!

# Answer
> 4 votes
# Perl 5, 31 bytes

```
$a=<>;$a/=++$i while$a>1;exit$a

```

Input is taken via STDIN, output is given via exit code (1 for factorial, 0 for non-factorial).

The input is divided by successive integers until it's either 1 or some fraction less than one, which is truncated into the result.

# Answer
> 4 votes
# Perl 6, 29 bytes

```
{($_,{$_/++$}...2>*).tail==1}

```

Test it

## Expanded:

```
{   # bare block lambda with implicit parameter ｢$_｣

  (              # generate a sequence

    $_,          # starting with the input

    {
      $_ / ++$   # divide previous element by an ever increasing number
                 # 1,2,3,4,5,6,7,8 ... *
    }

    ...          # keep generating until

    2 > *        # 2 is greater than what was generated
                 # ( 1 or a fractional number )

  ).tail == 1    # check if it ended at 1
}

```

# Answer
> 4 votes
# C (gcc), 33 bytes

```
e;f(n){n=n%++e?n==!(e=0):f(n/e);}

```

Note that some authors define "natural number" as *positive* integer. Hence I don't care that `f(0)` causes an infinite recursion.

# Answer
> 4 votes
# setlX, 32 bytes

```
f:=n|=>exists(x in{0..n}|n==x!);

```

Creates a function called `f` where your use your potential factorial as parameter.

It works with arbitrary integer size but it's fairly inefficient.

(by the way: this is my first participation at a programming puzzle)

# Answer
> 4 votes
## \>\<\>, ~~24~~ 22 bytes

*-2 bytes thanks to @Aaron*

I'm trying a new language (since my Mathematica licence expired…)

```
01\{=n;
?!\$1+:@*:{:}(

```

Try it online, or at the fish playground

Assumes the input number is already on the stack, and returns 0 or 1. It works by multiplying together the first *n* numbers until that stops being less than the input, and then printing 1 if it equals the input, and 0 if it doesn't.

# Answer
> 4 votes
# , ~~28~~ 22 bytes

```
scan()%in%gamma(1:171)

```

Try it online!

# Answer
> 4 votes
# C# (.NET Core), 68 bytes

```
bool f(System.Numerics.BigInteger n,int k=2)=>n<2||n%k<1&f(n/k,k+1);

```

Try it online!

Not the shortest solution, but works with really big numbers. The TIO link includes an example with `10000!`.

Here is a shorter version that uses `int` which has a maximum value of 2147483647.

# C# (.NET Core), 45 bytes

```
bool f(int n,int k=2)=>n<2||n%k<1&f(n/k,k+1);

```

Try it online!

Credit to @KevinCruijssen for golfing 3 bytes in total from both answers!

# Answer
> 4 votes
# Julia 1.0, 26 bytes

```
x->x in Base._fact_table64

```

Factorial is implemented as a lookup table in Julia, so lets just see if our value is in the table. Accurate for `Int64`, would be wrong for factorials that require a larger Integer type to represent.

Try it online!

# Answer
> 4 votes
# Vyxal, 3 bytes

```
Þ!c

```

Try it Online!

Updated to 2.16.0

This checks if the input is in an infinite list of factorials. Now you're probably wondering "but what if it isn't in the factorial list? A linear search won't ever terminate it'll just keep on going!" Well Vyxal is smart enough to know that in strictly ascending infinite lists of numbers, you stop once you reach a number bigger than what you're searching for.

# Answer
> 3 votes
## Mathematica, 20 bytes

```
!FreeQ[Range[#]!,#]&

```

other version to test big numbers (see comments)

```
Range[10^3]!~MemberQ~#&

```

tests up to 1000!

# Answer
> 3 votes
# Neim, 3 bytes

Uses some builtins added after this challenge was created.

```

```

Explanation:

```
Example input: 6
     Inclusive range [1 .. input]
      [[1, 2, 3, 4, 5, 6]
     Factorial each
      [[1, 2, 6, 24, 120, 720]]
     Check that the [cycled] input is in the list
      [1]

```

Try it!

# Neim, 8 bytes

```
Γ₁)

```

Explanation:

```
Example input: 6
         Inclusive range [1 .. input]
          [1, 2, 3, 4, 5, 6]
 Γ        For each...
           Inclusive range [1 .. element]
            [[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]]
           Product
            [1, 2, 6, 24, 120, 720]
           Check for equality with
    ₁       the first line of input
            [[0, 0, 1, 0, 0, 0]]
      )   End for each
         Select largest element
          [1]

```

Try it!

# Answer
> 3 votes
# Cubix, 24 bytes

```
U0O@1I1>-?1u>*w;W;@Orq)p

```

Try it online

Cubified

```
    U 0
    O @
1 I 1 > - ? 1 u
> * w ; W ; @ O
    r q
    ) p

```

We start by pushing `1`, `I`nput, `1` onto the stack. These will be our index, our target, and our accumulator, respectively.

We then loop. At each iteration, we subtract the accumulator from the input. If the result is 0, we're done, so we push `1`, `O`utput, and exit. If it's negative, we've gone too far, so we push `0`, `O`utput, and exit. Otherwise, we see

```
;p)*rq;
;         Pop the difference off the stack.
 p)       Move the index to the top of the stack and increment it.
   *      Multiply the accumulator by the index to get the next factorial.
    rq;   Put the stack back in the right order.

```

# Answer
> 3 votes
# TI-BASIC, 13 bytes

```
sum(Ans=seq(X!,X,1,69

```

Input is an integer in Ans.
Output is 1 if the input is a factorial, 0 if not.

Due to precision in `=` checks being limited to 10 decimal places, this program will produce erroneous answers for numbers whose length is \\$\>10\\$ digits.

**Explanation:**

```
        seq(X!,X,1,69  ;generate a list of all factorial numbers that
                       ;  TI-BASIC can store
    Ans=               ;equality check of the input against all members,
                       ;  1 if true, 0 if false
sum(                   ;sum the elements in the list
                       ;leave the result in Ans
                       ;implicit print of Ans

```

**Examples:**

```
720:prgmCDGF27
               1
25:prgmCDGF27
               0

```

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

# Answer
> 3 votes
# cQuents, 3 bytes

```
?$!

```

Try it online!

As I said in another question, cQuents is made for this.

```
?   # Query (Outputs if in the sequence)
 $! # Factorial

```

# Answer
> 3 votes
# Desmos, 34 bytes

```
max(\left\{[1,...,f]!=f,0\right\})

```

Try it in Desmos!

It simply finds the factorial of each number in an array from 0 to f (our input), and checks if f is in there using bounds.

# Answer
> 2 votes
# JavaScript (ES6), 71 bytes

This takes in input as function argument and `alert`s the output. Outputs `0` for falsey and `1` for truthy.

```
f=n=>n?n*f(n-1):1;g=(n,r=0,i=0)=>{while(i<=n){r=f(i)==n|r;i++}alert(r)}

```

## Explanation

The program consists of two functions, `f` and `g`. `f` is a recursive factorial-computing function, and `g` is the main function of the program. `g` *assumes* to have a single argument `n`. It defines a default argument `r` with a value of 0 and another default argument with a value of `0`. It, then, iterates over all the Integers from 0 to `n`, and, in each iteration, checks whether the function `f` applied over `i` (the current index) equals `n`, i.e. whether `n` is a factorial of `i`. If that happens to be the case, `r`'s value is set to 1. At the end of the function, `r` is `alert`ed.

## Test Snippet

(**Note:** *The snippet outputs using `console.log()` as nobody like too many of those pesky `alert()`s.*)

```
f=n=>n?n*f(n-1):1;g=(n,r=0,i=0)=>{while(i<=n){r=f(i)==n|r;i++}console.log(r)}

g(1)
g(2)
g(3)
g(4)
g(5)
g(6)
g(7)
g(8)
g(24)
g(120)
```

# Answer
> 2 votes
# PHP, 32 Bytes

prints -2 for true and -1 for false

```
for(;1<$argn/=++$x;);echo~$argn;

```

Try it online!

# Answer
> 2 votes
# Java 8, 59 bytes

```
i->{for(int j=1,c=0;j<=i;j*=++c)if(j==i)return 1;return 0;}

```

### Testcode

```
import java.util.function.IntFunction;
import java.util.stream.IntStream;

public class IsFactorial
{
    public static IntFunction<Integer> isFactorial = i->
    {
        for(int j=1,c=0;j<=i;j*=++c)
            if(j==i)return 1;return 0;
    };

    public static int[] truthyCases = {1,2,6,24,120};
    public static int[] falsyCases = {3,4,5,7,8};

    public static void main(String[] args)
    {
        System.out.println
        (
            IntStream.of(truthyCases)
                .allMatch(i->isFactorial.apply(i)==1)
            && IntStream.of(falsyCases)
                .allMatch(i->isFactorial.apply(i)==0)
        );
    }
}

```

# Answer
> 2 votes
# Charcoal, 24 bytes

```
ＮβＡ⟦⟧γＷ¬﹪βＬ⊞ＯγβＡ÷βＬγβ⁼β¹

```

Try it online! Prints `-` for true and nothing for false. Note: Link is to verbose form for ease of explanation.

# Answer
> 2 votes
## QBIC, ~~21~~ 19 bytes

```
[:|q=q*a~q=b|_x1}?0

```

Explanation

```
[:|     Start a FOR loop from 1 to n
q=q*a   q starts as 1 and is multiplied by the FOR loop counter
        consecutively: q=1*1, *2, *3, *4 ... *n
~q=b|   If that product equals n
_x1     Then quit, printing a 1
}       Close the IF and the FOR
?0      If we're here, we didn't quit early and didn't find a factorial, print 0

```

---

Previously

```
[:|q=q*a┘c=c+(q=b)}?c

```

Explanation:

```
[:|         Start a FOR loop from 1 to n
q=q*a       q starts as 1 and is multiplied by the FOR loop counter
            consecutively: q=1*1, *2, *3, *4 ... *n
┘           Syntactic line break
c=c+        c starts out at 0 and then keeps track of
    (q=b)       how often our running total == n
}           Closes the FOR-loop
?c          Print c, which is 0 fir non-factorials and -1 otherwise.

```

# Answer
> 2 votes
## C, ~~42~~ ~~41~~ 38 bytes

*-3 bytes by @KritixiLithos!*

```
m;f(float n){for(;n>1;n/=++m);m=n==1;}

```

Try it online!

# Answer
> 2 votes
# Befunge-98, ~~39~~ 38 bytes

```
&1s #;:30g%;@.;#0_30g:1+30p/:1-#;!#1_;

```

Try it online!

Funge storage is only byte-sized, so the input number has to be kept on stack.

```
&1s #;:30g%;@.;#0_30g:1+30p/:1-#;!#1_;
&1s                                     n = read(), k = 1
     ;:30g%;     _                      S: if n % k != 0 goto Z
                  30g      /            n /= k
                     :1+30p             k += 1
                            :1-  !  _   if n != 1 goto S
                                ;  1    push(1), goto P
                0                       Z: push(0)
            @.;                         P: print()

```

# Answer
> 2 votes
## Haskell, ~~42~~ 41 bytes

```
f 0=1
f a=a*f(a-1)
i x=elem x f<$>[1..x]

```

sample ghci output:

```
λ> i 0
False
*Main
λ> i 1
True
*Main
λ> i 2
True
*Main

```

# Answer
> 2 votes
# Templates Considered Harmful, 99 bytes

```
Fun<Ap<Fun<If<Eq<A<1>,T>,T,Eq<Rem<A<1>,A<2>>,F>,Ap<A<0>,Div<A<1>,A<2>>,Add<A<2>,T>>,F>>,A<1>,I<2>>>

```

Try it online!

Ungolfed:

```
Fun<Ap<Fun<If<Eq<A<1>, T>,
              T,
              Eq<Rem<A<1>, A<2>>, F>,
              Ap<A<0>, Div<A<1>, A<2>>, Add<A<2>, T>>,
              F>>,
       A<1>, I<2>>>

```

Divides by 2, 3, 4… until hits 1 or non-zero remainder.

# Answer
> 2 votes
# Ruby, 34 bytes

```
->a{x=1;(1..a).any?{|y|(x*=y)==a}}

```

Try it online!

# Answer
> 2 votes
## C#, 43 40 bytes, 41 bytes fallback

Uses a `for` loop to increment a number to divide the input by until the variable containing the input is no longer more than one. Returns `false` if the input is a factorial, `true` otherwise. The expression type is `Func<dynamic, System.Func<dynamic, bool>>` and it can take the same input for both calls. In case that isn't allowed, the fallback answer is `System.Func<dynamic, bool>`.

## Short Answer

Try it online!

```
m=>s=>{for(s=2f;m>1;)m/=s++;return m<1;}

```

## Fallback

Try it online!

```
m=>{for(var s=2f;m>1;)m/=s++;return m<1;}

```

# Answer
> 2 votes
## T-SQL 143 Bytes

```
create function a(@ int)
returns int begin
declare @a int=1,@b int=1
while @b<@
select @b*=@a,@a+=1
return case @b when @ then 1 else 0 end
end

```

Playing code golf with SQL gives me results like when I really golf!

Analysis:

```
create function a(@ int)
returns int begin

```

Ugh why do I have so many required characters to create a SQL function

```
declare @a int=1,@b int=1

```

We need a variable for our current factorial value, and a variable for the iteration to multiply by.

```
while @b<@

```

While our current factorial value is less than our input value, keep iterating through the loop.

```
select @b*=@a,@a+=1

```

Multiply our factorial value by the iteration value, and add one to the iteration value for the next loop.

```
return case @b when @ then 1 else 0 end

```

If our factorial value equals our input value, then it's going to return 1 for true, and if it's not, then that means it's not a factorial value and it's false.

```
end

```

# Answer
> 2 votes
# Pyt, 5 bytes

```
←Đř!∈

```

Explanation:

```
←           Get input and put on stack
 Đ          Duplicate top of stack
  ř         Push [1,...,top of stack] to stack
   !        Calculate element-wise factorial of the array
    ∈       Is input in factorial array?

```

# Answer
> 2 votes
# SmileBASIC, 37 bytes

```
INPUT N
WHILE N>1A=A+1N=N/A
WEND?N==1

```

Divides N by increasing numbers until N is less than or equal to 1. If N was a factorial, it will be 1 at the end.

Examples:

```
8 (÷1)-> 8 (÷2)-> 4 (÷3)-> 4/3 (÷4)-> 1/3 (end)
6 (÷1)-> 6 (÷2)-> 3 (÷3)-> 1 (end)

```

# Answer
> 2 votes
# C++, ~~87~~ 77 bytes

(I'm aware this is a bit old, but I figured I'd try my luck since the current C++ answer is at 92 bytes)

```
int f(int a){a=a?a*f(a-1):1;}int c(int a,int b=0){a=f(b)-a?a-b?c(a,b+1):0:1;}

```

The function for the check is `c`, the `f` function is purely to calculate the factorial

Ungolfed with comments:

```
int f(int a)
{
    // In some systems the last expression evaluated will be
    // the return value, this is utilizing that, as it assigns
    // a to a, and if that is 0, then the last espression will
    // have been 1, else it will be a * f(a-1)
    a=a ? a*f(a-1) : 1;
}

int c(int a,int b=0)
{
    // This works in the same way but over 2 levels
    // If f(b)==a then a=f(b)-a is 0, which means it'll
    // evalute 1, truthy, but if it's not zero, then it
    // Checks if a==b, if yes then it's 0, falsy because
    // we've checked all numbers, and if it's not 0, then
    // it calls c again with b+1
    a = f(b) - a ? a - b ? c(a,b+1) : 0 : 1;
}

```

Try it online (Thanks to @Jonathan Frech for the 77 bytes and link)

I found this recursive method much more shorter than a loop, especially with the default argument that stores the counter.

# Answer
> 2 votes
# Alchemist, ~~265~~ 264 bytes

```
_->a+In_b+q
q+b->q+h+c
q+0b->r
r+h->r+b
r+0h->s
s+i->s+j+m
s+0i->t
t+a->t+d
t+0a->u
u+d->u+a+n
u+0d->v
v+n->v+h
v+0n+m->t
v+0n+0m->p
p+a->p
p+0a->w
w+h->w+a+f
w+j->w+i
w+0j+0h->i+x
x+b+f->x
x+0b+0f->Out_"1"
x+0b+f->Out_"0"
x+b+0f->y
y+b->y
y+0b->z
z+c->z+b
z+0c->q

```

Outputs `1` if it's a factorial and `0` otherwise: Try it online or test the first *n* factorials~~!~~

## Ungolfed

The non-determinism comes from the rules

```
w+h->w+a+f     # s6 +  tmp -> s6 + accum + factorial
w+j->w+i       # s6 + counter_copy -> s6 + counter
w+0j+0h->i+x   # s6 + 0counter_copy + 0tmp -> counter + s7

```

which could be serialised to

```
w+h->w+a+f   # s6 +  tmp -> s6 + accum + factorial
w+0h->o      # s6 + 0tmp -> _s6
o+j->o+i     # _s6 +  counter_copy -> _s6 + counter
o+0j->i+x    # _s6 + 0counter_copy -> counter + s7

```

such that the `tmp`-atom will be duplicated first and only then `counter_copy` renamed to `counter` and incremented:

Try it online! (see debugging output)

But it should be clear that this non-determinism will not change the result of the complete computation:

```
# initialize accumulator & read input
_ -> accum + In_input + s0

# duplicate the input
s0 +  input -> s0 + tmp + input_copy
s0 + 0input -> s1

s1 +  tmp -> s1 + input
s1 + 0tmp -> s2

# duplicate the counter
s2 +  counter -> s2 + counter_copy + multiplier
s2 + 0counter -> s3

# duplicate the accumulator: factor <- accum
s3 +  accum -> s3 + dup
s3 + 0accum -> s4

s4 +  dup -> s4 + accum + factor
s4 + 0dup -> s5

s5 + 0factor +  multiplier -> s3   # while multiplier > 0:
s5 +  factor -> s5 + tmp           #   add factor: tmp += factor

# when "loop" is done, cleanup accum and continue
s5 + 0factor + 0multiplier +  accum -> s5
s5 + 0factor + 0multiplier + 0accum -> s6

# tmp holds the next factorial, keep it (non-deterministic)
s6 +  tmp -> s6 + accum + factorial
# restore counter

# restore counter and increment it
s6 + counter_copy -> s6 + counter
s6 + 0counter_copy + 0tmp -> counter + s7

# compare current factorial and input
s7 +  input +  factorial -> s7
s7 + 0input + 0factorial -> Out_"1"  # if factorial == input: done (success)
s7 + 0input +  factorial -> Out_"0"  # elif factorial > input: done (current factorial exceeds input)
s7 +  input + 0factorial -> s8       # input > factorial: try next factorial

# cleanup from before
s8 +  input -> s8
s8 + 0input -> s9

# restore input and continue
s9 +  input_copy -> s9 + input
s9 + 0input_copy -> s0

```

Try it online!

# Answer
> 2 votes
# C, 50 bytes

```
p,i;f(int n){p=1;for(i=1;p<n;p*=i++);return p==n;}

```

Special Thanks to Jo King for shortening the program.

# Answer
> 2 votes
# Fortran (GFortran), 57 bytes

```
read*,i
k=1
do j=1,i
k=k*j
if(i==k)l=1
enddo
print*,l
end

```

Try it online!

On some compilers may result in gibberish on false-y due to uninitialised `l`. Can be solved with 3 bytes (`l=0`) or compiler flags (e.g. `-finit-integer=0`). Strictly 1 is not a truthy in Fortran, but spec specified 1/0 for true/false.

# Answer
> 2 votes
# Python 3.8 (pre-release), 47 bytes

```
lambda n,t=1:n in[t:=t*i for i in range(1,n+1)]

```

Try it online! This is not a Python winner, but it does showcase the walrus operator `:=` in a scenario that isn't the typical *look at me I'm golfing this and writing really obfuscated Python code* :)

# Answer
> 2 votes
# Add++, 10 bytes

```
L,R€R€b*Ae

```

Try it online!

## How it works

```
L,		; Define the main function that takes one argument, x
		; Example: x = 24		STACK = [24]
	R	; Range				STACK = [[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]]
	€R	; Range for each		STACK = [[[1] [1 2] [1 2 3] ... [1 2 3 ... 22 23 24]]
	€b*Bh	; Product for each		STACK = [[1 2 6 ... 620448401733239439360000]]
	Ae	; Is x in the array?		Returns 1

```

# Answer
> 2 votes
# Factor, 56 bytes

```
[| x | 1 1 [ dup x < ] [ [ 1 + dup ] dip * ] while x = ]

```

Try it online!

There may be a shorter solution using division, since it won't involve a separate accumulator and won't require `| x |`, but I can't find it yet.

### Using `/`, 59 bytes

```
[ 1 swap [ dup 1 > ] [ [ 1 + dup ] dip swap / ] while 1 = ]

```

Try it online!

# Answer
> 2 votes
# Python 2, 35 bytes

```
f=lambda n,d=1:n<2or n%d<f(n/d,d+1)
```

Attempt This Online!

-2 bytes thanks to @dingledooper

# Answer
> 2 votes
## PHP4 (39 chars)

Given *$argv\[1\]* as a command line argument, the script will answer to stdout and silence the notice.

```
for($n=$argv[1];1<@$n/=++$_;);echo~~$n;

```

## C (std=c99, 44 chars)

The function **f** will answer up to `18!`.

```
i;f(double n){for(i=1;n>1;n/=++i);return n;}

```

Edit : saved 2 chars by properly declaring the integer `i`, thanks to @ceilingcat.

# Answer
> 1 votes
# JavaScript (ES6), ~~60~~ 58 bytes

```
a=>[...Array(a).keys()].some(b=>(f=c=>c?c*f(c-1):1)(b)==a)

```

# Answer
> 1 votes
# CJam, 9 bytes

```
q~_,:m!e=

```

Try it online!

This outputs 1 if the input is a factorial, 0 otherwise.

Explanation:

```
q~           Read the input
  _,         Create array [0,...,Input-1]
    :m!      Factorial of each element of the array
       e=    Check if any element is equal to input

```

# Answer
> 1 votes
## Clojure, 39 bytes

```
#(=((set(reductions *'(range 1 %)))%)%)

```

Calculating factorials up-to `n` seems to be the best way to go. `*'` supports arbitrary precision, but the runtime and memory usage of this implementation are quite bad for larger inputs. Returns `true` or `false`.

If truthy value was allowed to vary (returns the input number or `nil`) this would be 35 bytes:

```
#((set(reductions *'(range 1 %)))%)

```

For small input arguments you could use `*` instead of `*'`.

# Answer
> 1 votes
# , 9 bytes

```
e.!@i.@>:

```

Try it online!

# Answer
> 1 votes
# Pyth, 5 bytes

```
/.!MS

```

online interpreter link

# Answer
> 1 votes
# Python 2 - ~~*48*~~ 44 bytes

Thanks, @JonathanAllan, saved 4 bytes

Of course, not as short as the other answer, but doing stuff the old-fashion way:

```
n,x=input(),1.
while n>1:x+=1;n/=x
print n<1

```

Try It Online!

# Answer
> 1 votes
## C#, 99 bytes

```
a=>{for(int i=0;i<22;i++){var b=1;for(int j=2;j<i;j++){b*=j;}if(a==b){return true;}}return false;};

```

It checks, if the input is one of the first 22 factorials, if yes it returns true, otherwise false.

# Answer
> 1 votes
# C#, 69 62 60 Bytes

```
n=>{int l=1,i=1,r=0;for(;i<13;i++)r=(l*=i)==n?1:r;return r;}

```

With line breaks:

```
n=> {
        int l = 1, i = 1, r = 0;
        for (; i < 13; i++)
            r = (l *= i) == n
                ? 1
                : r;
        return r;
    }

```

Or as a whole method (**79 71 69 Bytes**):

```
int F(int n){int l=1,i=1,r=0;for(;i<13;i++)r=(l*=i)==n?1:r;return r;}

```

With line breaks:

```
int F(int n)
{
    int l = 1, i = 1, r = 0;
    for (; i < 13; i++)
        r = (l *= i) == n
            ? 1
            : r;
    return r;
}

```

*Saved 2 Bytes thanks to Arjun*

# Answer
> 1 votes
# C, 57 bytes

More of a novelty solution more than anything else, just to have some fun with recursion. An iterative solution will most likely be shorter.

```
g(d,n){n<2?putchar(n+47):g(d+1,n/d*!(n%d));}f(n){g(1,n);}

```

# Answer
> 1 votes
# Pari/GP, 23 bytes

```
n->#[x|x<-[1..n],x!==n]

```

Try it online!

# Answer
> 1 votes
# TI-Basic, 12 bytes

```
sum(Ans=seq(X!,X,1,Ans

```

This creates a list of all factorials up to the input's factorial, compares each one to the input, and returns the sum of all of the comparisons, which will be 1 if one of the factorials is equal to the input, or 0 if none are. This sum is implicitly returned as it is on the last line of the program.

Call with `53:prgmNAME`. Overflows on inputs over 69; to avoid this, use `sum(Ans=seq(X!,X,1,1+sqrt(Ans` for 15 bytes

# Answer
> 1 votes
# Actually, 5 bytes

```
;R♂!c

```

Try it online!

-2 bytes from Erik the Outgolfer's suggestion on a different answer

Explanation:

```
;R♂!c
;        duplicate input
 R       range(1, input+1)
  ♂!     factorial of each number in range
    c    does the list contain the input?

```

# Answer
> 1 votes
# **Ruby, 39 bytes**

```
->a{(1..a).any?{|e|Math.gamma(e+1)==a}}

```

# Answer
> 1 votes
# Perl 6, 17 bytes

```
{$_∈[\*] 1..$_}

```

Checks whether `$_`, the argument, is a member of the triangular multiplication reduction `(1, 1*2, ..., 1*2*...*$_)`.

This does a LOT of unnecessary math for larger inputs, but hey, it's short!

# Answer
> 1 votes
# Japt, 9 bytes

This is my first Japt answer (and first Esolang answer)!

```
Uõl d_==U

```

An optimal solution already exists but that's not a reason for not posting this answer!

Try it online!

*Thanks to @ETHproductions and @Shaggy for helping me out in the Japt Chatroom when I was stuck! And special thanks to @ETHproductions for making this language! It feels so good to code in Japt!*

# Answer
> 1 votes
# Tcl, 69 bytes

```
proc F n {incr p
while \$p<$n {set p [expr $p*[incr i]]}
expr $p==$n}

```

Try it online!

# Answer
> 1 votes
# Japt, 4 bytes

```
õÊøU

```

Try it online!

# Answer
> 1 votes
# Zephyr, 86 bytes

```
input n as Integer
set i to 1
set f to 1
while f<n
inc i
set f to f*i
repeat
print f=n

```

Try it online!

`f` successively takes the value of every factorial from `1` on up, until it is no longer less than the input number `n`. If `f` is now equal to `n`, then `n` is a factorial and we output `true`; otherwise, `n` is not a factorial and we output `false`.

# Answer
> 1 votes
# Retina, 31 bytes

```
^
_
+a`(_+) (\1)+
_$1 $#2*
 _$

```

Try it online!

---

Takes as input a unary number with `_` as tally mark

# Answer
> 1 votes
# Forth (gforth), 58 bytes

Surprisingly, the shortest method I could find to do this was iterating the factorial numbers and comparing them to the input.

```
: f >r 1 1 begin 1+ tuck 1- * tuck r@ >= until r> nip = ;

```

Try it online!

### Explanation

```
>r              \ place the input on the return stack (saves a lot of stack operations)
1 1             \ place the current factorial-value and the index on the stack
begin           \ start an indefinite loop
   1+ tuck 1-   \ increment the index, save a copy, and then decrement again
   * tuck       \ multiply the factorial and the index and save a copy
   r@           \ copy the input from the return stack
   0>=          \ check if it's greater than or equal to the factorial-value
until           \ end the indefinite loop
r> nip          \ move the input back to the normal stack and delete the index
=               \ compare the input and the final factorial value

```

# Answer
> 1 votes
# CJam, 10 bytes

```
q~_),:m!&,

```

Try it online!

Uses similar logic as @FrodCube, but instead calculates set intersection and gets the length of the input. If the last `,` is dropped, you still get truthy/falsy values, but they are not consistent.

# Answer
> 1 votes
## F#, 79 bytes

```
let rec f x=if x<2 then 1 else f(x-1)*x
let i n=Seq.map f{0..n}|>Seq.contains n

```

Try it online!

Maps each number from 0 to `n` inclusive to its factorial value (through the recursive function `f`), and checks to see if any of the mapped numbers are `n`.

# Answer
> 1 votes
# CJam, 15 bytes

```
q~_,{)m!}%#-1=!

```

probably not the shortest answer but it's my first attempt with CJam

Explanation:

```
    q~_        Get the input and make a copy on the stack
    ,{)m!}%    Factorial all numbers from 1 to input
    #          see if input is in array
    -1=!       if input isn't in array return false otherwise return true

```

# Answer
> 1 votes
# Common Lisp, 56 bytes

```
(lambda(i)(do((c 0)(j 1(*(incf c)j)))((<= i j)(= j i))))

```

Try it online

# Answer
> 1 votes
# Brain-Flak, 154 bytes

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

```

Try it online!

# Answer
> 1 votes
# Tidy, 18 bytes

```
{x:x in(!)on[1,x]}

```

Try it online!

Simply tests if `x` is in the list generated by taking the factorial of each element in `[1, x]`.

# Answer
> 1 votes
# GolfScript, 17 bytes

```
~.),{,1\{)*}/}%?)

```

Try it online!

# Explanation

```
~                  # Evaluate the input
 .                 # Duplicate the value
  )                # Increment the value
   ,               # Generate range from 1 to input
    {        }%    # Map every item
     ,             # Generate a to-0 range
      1\           # Make the initial product 1
        {  }/      # Foreach over the product:
         )*        # Multiply by the value incremented by 1
               ?)  # Index, and then logicize it

```

# Answer
> 1 votes
# Burlesque, 13 bytes

```
riJro?!jFi0>=

```

Try it online!

If you accept -1 as falsey (technically isn't in burlesque) and \>0 as truthy can save 3 bytes.

```
riJ # Read as int and duplicate on stack
ro  # Range from [1,N]
?!  # Factorial each
jFi # Find the index of the element == N
0>= # Found index

```

# Answer
> 1 votes
# ink, 52 bytes

```
=t(n)
~temp f=1
-(l){n<f:{n==1}->->}
~n=n/f
~f++
->l

```

Try it online!

Assumes the input is a floating point number. If the number is integer-type, the division on line 4 truncates the quotient, which can cause false positives.
Prints its output (1 or 0) directly to stdout. Because ink.

### Ungolfed

```
== check_if_factorial(input) ==
~ temp iterator = 1
- (loop)
{
    - iterator < input:
        {n == 1 : 1 | 0}
        ->->
}
~ input = input / iterator
~ iterator++
-> loop

```

# Answer
> 0 votes
# 2Col, 5 bytes \[non-competing\]

```
F!
$^

```

Try it in 2CollIDE

Basically the same as the Jelly answers. Link leads to the current 2Col interpreter in TIO, with the above code already inserted. 3rd argument is input.

2Col is a language where each line is a 2 character expression of some form. It's what I like to call an "Accumulator-based" language. It works like Stack-based languages, except the "stack" can only contain a single item.

### Explanation:

```
      Implicit input to Cell
F!    Return [1!, 2!, ... n!]
$^    Return whether above return value contains Cell value
      Implicit: Print final line's return value

```

# Answer
> 0 votes
# Axiom, 67 bytes

```
f(x:NNI):Boolean==(i:=2;r:=1;repeat(r>=x=>break;r:=r*i;i:=i+1);r=x)

```

some test

```
(12) -> [[i,f(i)] for i in [0,1,2,3,6,24,25,120,720]]
   (12)
   [[0,false], [1,true], [2,true], [3,false], [6,true], [24,true], [25,false],
    [120,true], [720,true]]
                                                      Type: List List Any

```

# Answer
> 0 votes
# Tcl, 71 bytes

```
incr p
while \$p<$argv {set p [expr $p*[incr i]]}
puts [expr $p==$argv]

```

Try it online!

# Answer
> 0 votes
# Python 3, 92 bytes

```
f=lambda n,i='1':n<2or(eval(i)==n if eval(i)>=n else f(n,i+'*%d'%(int(i.split('*')[-1])+1)))

```

Try it online!

This is the first thing I thought of seeing this challenge, but it didn't turn out as well as I had it in my head, easily beaten by other solutions.

Thanks to lambda for noticing a bug in my submission.

# Answer
> 0 votes
## JavaScript, 124 bytes

I am nub so here it is:

```
a=(i)=>{r=1;n=0;while(n>=0){n++;r=r*n;if(i==r){console.log(i,"truthy:",n+"!");break;}else{console.log(i,"falsey:",n+"!");}}}

```

This link may or may not work. If it does, click run and then type "a(24)" or "a(120)" etc. If you pass-in a non-factorial int, it will run infinitely... so don't do that.

# Answer
> 0 votes
# Excel, 24 bytes

```
=OR(A1=FACT(ROW(1:170)))

```

# Answer
> 0 votes
# Vyxal 3.0.0beta.1, 4 bytes

```
0R!C

```

Try it online! (link is to literate version)

## Explained

```
0 range ## Range [input, 0]
fact    ## Factorial of each
count   ## Count of input in ^

```

# Answer
> 0 votes
# Thunno `D`, \\$ 4 \log\_{256}(96) \approx \\$ 3.29 bytes

```
RFsc

```

Attempt This Online!

Outputs \\$0\\$ (falsy) or \\$1\\$ (truthy).

#### Explanation

```
RFsc  # Implicit input
R     # Push range(0, input)
 F    # Factorial of each
  sc  # Input is in this list?
      # Implicit output

```

---
Tags: code-golf, math, number, decision-problem
---


title: All of the Boards

text:
# Question
Title: All of the Boards
Problem source: https://oj.vnoi.info/problem/backtrack\_j

We have these two shapes:

```
#.
##

```

and

```
.#
##

```

Let's call the first shape the L and the second shape the flipped L.

On a 4x4 board, there are 16 cells. Each cell can be either free or occupied. In all the illustrations, `#` represents an occupied cell and `.` represents a free cell.

Your job is to print **all 4x4 boards** that can be completely filled using the L shape and the flipped L shape. You are not allowed to rotate or flip the shapes, but you can put them anywhere you want as long as the shape isn't clashing with existing occupied cells. **You are allowed to represent the boards in any reasonable format and print them in any order.**

Here is an example of a board that can be filled:

```
.##.
....
.##.
....

```

We can perform these steps to fill the whole board.

Step 1: Fill an L at the top left corner

```
###.
##..
.##.
....

```

Step 2: Fill a flipped L at the top right corner

```
####
####
.##.
....

```

Step 3: Fill an L at the bottom left corner

```
####
####
###.
##..

```

Step 4: Fill a flipped L at the bottom right corner

```
####
####
####
####

```

Here is an example of a board that can't be filled:

```
#...
....
....
....

```

No matter how hard you try, it's just impossible to fill the board.

Sample output:

```
###.
#...
....
....

##.#
#...
....
....

#.##
...#
....
....

.###
...#
....
....

####
##.#
....
....

####
#.##
....
....

#.#.
....
#.#.
....

.##.
....
#.#.
....

#..#
....
#.#.
....

.#.#
....
#.#.
....

###.
##..
#.#.
....

##.#
##..
#.#.
....

##.#
#..#
#.#.
....

#.##
#..#
#.#.
....

#.##
..##
#.#.
....

.###
..##
#.#.
....

####
####
#.#.
....

#.#.
....
.##.
....

.##.
....
.##.
....

#..#
....
.##.
....

.#.#
....
.##.
....

###.
##..
.##.
....

##.#
##..
.##.
....

##.#
#..#
.##.
....

#.##
#..#
.##.
....

#.##
..##
.##.
....

.###
..##
.##.
....

####
####
.##.
....

#.#.
....
#..#
....

.##.
....
#..#
....

#..#
....
#..#
....

.#.#
....
#..#
....

###.
##..
#..#
....

##.#
##..
#..#
....

##.#
#..#
#..#
....

#.##
#..#
#..#
....

#.##
..##
#..#
....

.###
..##
#..#
....

####
####
#..#
....

#.#.
....
.#.#
....

.##.
....
.#.#
....

#..#
....
.#.#
....

.#.#
....
.#.#
....

###.
##..
.#.#
....

##.#
##..
.#.#
....

##.#
#..#
.#.#
....

#.##
#..#
.#.#
....

#.##
..##
.#.#
....

.###
..##
.#.#
....

####
####
.#.#
....

###.
#...
#...
##..

##.#
#...
#...
##..

#.##
...#
#...
##..

.###
...#
#...
##..

####
##.#
#...
##..

####
#.##
#...
##..

###.
#...
..#.
##..

##.#
#...
..#.
##..

###.
.#..
..#.
##..

##.#
.#..
..#.
##..

##.#
...#
..#.
##..

#.##
...#
..#.
##..

####
#.##
..#.
##..

####
.###
..#.
##..

#.#.
....
###.
##..

.##.
....
###.
##..

#..#
....
###.
##..

.#.#
....
###.
##..

###.
##..
###.
##..

##.#
##..
###.
##..

##.#
#..#
###.
##..

#.##
#..#
###.
##..

#.##
..##
###.
##..

.###
..##
###.
##..

####
####
###.
##..

###.
#...
...#
##..

##.#
#...
...#
##..

###.
.#..
...#
##..

##.#
.#..
...#
##..

##.#
...#
...#
##..

#.##
...#
...#
##..

####
#.##
...#
##..

####
.###
...#
##..

#.#.
....
##.#
##..

.##.
....
##.#
##..

#..#
....
##.#
##..

.#.#
....
##.#
##..

###.
##..
##.#
##..

##.#
##..
##.#
##..

##.#
#..#
##.#
##..

#.##
#..#
##.#
##..

#.##
..##
##.#
##..

.###
..##
##.#
##..

####
####
##.#
##..

##.#
#...
#...
#..#

#.##
#...
#...
#..#

#.##
..#.
#...
#..#

.###
..#.
#...
#..#

####
###.
#...
#..#

#.##
...#
#...
#..#

.###
...#
#...
#..#

####
##.#
#...
#..#

###.
#...
...#
#..#

##.#
#...
...#
#..#

###.
.#..
...#
#..#

##.#
.#..
...#
#..#

##.#
...#
...#
#..#

#.##
...#
...#
#..#

####
#.##
...#
#..#

####
.###
...#
#..#

#.#.
....
##.#
#..#

.##.
....
##.#
#..#

#..#
....
##.#
#..#

.#.#
....
##.#
#..#

###.
##..
##.#
#..#

##.#
##..
##.#
#..#

##.#
#..#
##.#
#..#

#.##
#..#
##.#
#..#

#.##
..##
##.#
#..#

.###
..##
##.#
#..#

####
####
##.#
#..#

#.#.
....
#.##
#..#

.##.
....
#.##
#..#

#..#
....
#.##
#..#

.#.#
....
#.##
#..#

###.
##..
#.##
#..#

##.#
##..
#.##
#..#

##.#
#..#
#.##
#..#

#.##
#..#
#.##
#..#

#.##
..##
#.##
#..#

.###
..##
#.##
#..#

####
####
#.##
#..#

##.#
#...
#...
..##

#.##
#...
#...
..##

#.##
..#.
#...
..##

.###
..#.
#...
..##

####
###.
#...
..##

#.##
...#
#...
..##

.###
...#
#...
..##

####
##.#
#...
..##

##.#
#...
.#..
..##

#.##
#...
.#..
..##

#.##
..#.
.#..
..##

.###
..#.
.#..
..##

####
###.
.#..
..##

#.##
...#
.#..
..##

.###
...#
.#..
..##

####
##.#
.#..
..##

###.
#...
...#
..##

##.#
#...
...#
..##

#.##
...#
...#
..##

.###
...#
...#
..##

####
##.#
...#
..##

####
#.##
...#
..##

#.#.
....
#.##
..##

.##.
....
#.##
..##

#..#
....
#.##
..##

.#.#
....
#.##
..##

###.
##..
#.##
..##

##.#
##..
#.##
..##

##.#
#..#
#.##
..##

#.##
#..#
#.##
..##

#.##
..##
#.##
..##

.###
..##
#.##
..##

####
####
#.##
..##

#.#.
....
.###
..##

.##.
....
.###
..##

#..#
....
.###
..##

.#.#
....
.###
..##

###.
##..
.###
..##

##.#
##..
.###
..##

##.#
#..#
.###
..##

#.##
#..#
.###
..##

#.##
..##
.###
..##

.###
..##
.###
..##

####
####
.###
..##

##.#
....
....
####

#.##
....
....
####

####
#.#.
....
####

####
.##.
....
####

####
#..#
....
####

####
.#.#
....
####

##.#
#...
##..
####

#.##
#...
##..
####

#.##
..#.
##..
####

.###
..#.
##..
####

####
###.
##..
####

#.##
...#
##..
####

.###
...#
##..
####

####
##.#
##..
####

###.
#...
#..#
####

##.#
#...
#..#
####

#.##
...#
#..#
####

.###
...#
#..#
####

####
##.#
#..#
####

####
#.##
#..#
####

###.
#...
..##
####

##.#
#...
..##
####

###.
.#..
..##
####

##.#
.#..
..##
####

##.#
...#
..##
####

#.##
...#
..##
####

####
#.##
..##
####

####
.###
..##
####

#.#.
....
####
####

.##.
....
####
####

#..#
....
####
####

.#.#
....
####
####

###.
##..
####
####

##.#
##..
####
####

##.#
#..#
####
####

#.##
#..#
####
####

#.##
..##
####
####

.###
..##
####
####

####
####
####
####

```

This is , the shortest code (in bytes) wins.

# Answer
# Nekomata, 28 bytes

```
2r↕1:ÐÐ3r~ᵑᵐç3r~ᵑçaᵐᶜ{0*}∑2<

```

Attempt This Online!

Outputs 215 4×4 matrices using `1`s for free and `0`s for occupied cells.

### Explanation

```
2r↕1:ÐÐ3r~ᵑᵐç3r~ᵑçaᵐᶜ{0*}∑2<
2r↕1:ÐÐ                         Push [[0,1],[1,1]] or [[1,0],[1,1]]
       3r~ᵑᵐç                   Prepend 0, 1 or 2 zeros to each sublist
             3r~ᵑç              Prepend 0, 1 or 2 zeros to the list
                  a             Get all possible values as a list
                   ᵐᶜ{0*}       Optionally multiply each value by zero
                         ∑      Take the sum
                          2<    Check if all numbers in the result is less than 2

```
> 3 votes

# Answer
# Python, 122 bytes (-2 thanks to @ovs)

```
A=0,19,35
for d in(2,16)*2:A={x|y*d for x in A for y in A if 1>x&y*d}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))

```

Attempt This Online!

#### Previous Python, 124 bytes (-1 thanks to @xnor)

```
A={0,19,35}
for d in(2,16)*2:A={x|y*d for x in A for y in A if 1>x&y*d}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))

```

Attempt This Online!

#### Previous Python, 126 bytes

```
A={0,19,35}
for d in(1,4)*2:A|={(x|y<<d)*(1>x&y<<d)for x in A for y in A}
for i in A:print(f"{i:019_b}_".translate(33*"#.\n"))

```

Attempt This Online!
> 9 votes

# Answer
# Wolfram Language (Mathematica), ~~249~~ ~~230~~ ~~224~~ 210 bytes

```
(r={f=Table[1,{4},{4}]};p={e={1,1},{0,2},{2,0}};q=Flatten[Table[ArrayPad[k,{i,j}],{k,{{{1,0},e},{{0,1},e}}},{i,p},{j,p}],2];(a=#;r=Join[r,v=Select[a-#&/@q,AllTrue[#,(#>=0&),2]&]];Table[#0[e],{e,v}])&@f;Union@r)

```

Try it online!

Recursive solution based on the next fact :
If given matrix is valid and we remove from it "L" or "anti-L", then the new matrix will be valid too.

All valid boards in a single picture:

Ungolfed version as explanation:

```
init = Table[1, {4}, {4}];
result = {init};
forms = {{{1, 0}, {1, 1}}, {{0, 1}, {1, 1}}};
pads = {{1, 1}, {0, 2}, {2, 0}};
patterns =
  Flatten[Table[
    ArrayPad[k, {i, j}], {k, forms}, {i, pads}, {j, pads}], 2];
main[arr_] :=
  With[{nextValid =
     Select[arr - # & /@ patterns, AllTrue[#, (# >= 0 &)] &, 2]},
   result = Join[result, nextValid];
   main[#] & /@ nextValid
   ];
main@init;
output = Union@result;

```

The longest part of code is a preparing of matrix patterns.
I'll try to golf it harder!
That's all. Add a some mad golfing, and can’t improve the algorithm anymore (
> 7 votes

# Answer
# JavaScript (ES6), 159 bytes

A rather lenghty port of loopy walt's answer.

```
f=(A=new Set([0,19,35]),d=2)=>(B=[...A])[99]?B.map(v=>(g=k=>k--?"#."[v>>k&1]+[`
`[k&3]]+g(k):'')(16)).join`
`:f(A,d^18,B.map(x=>B.map(y=>x&y*d||A.add(x|y*d))))

```

Try it online!
> 4 votes

# Answer
# Haskell, 152 bytes

```
import Data.List
r=[[[r,c]|r<-[0..3],c<-[0..3],notElem[r,c]l]|l<-concat<$>subsequences[[[r-1,c+t],[r,c],[r,c+1]]|r<-[1..3],c<-[0..2],t<-[0,1]],l==nub l]

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 33 bytes

```
56āδš<TÝ37SKδ+€`æε˜ÐÙQiX16Å0rǝ4ô,

```

Outputs as a list of matrices of 0s for `.` and 1s for `#`.

Try it online or try it online with pretty-printing footer. (Pretty slow, so only outputs about 175 of them before timing out on TIO.)

**Explanation:**

Step 1: Push the 0-based indices of the two shapes at every possible position on the (flattened) 4x4 board:

```
56āδš<            # Push the indices of the two L-shapes in the top-left corner of the
                  # (flattened) board:
56                #  Push 56
  ā               #  Push a list in the range [1,length] (without popping): [1,2]
   δ              #  Apply double-vectorized:
    š             #   Prepend: [[1,5,6],[2,5,6]]
     <            #  Decrease each inner value by 1: [[0,4,5],[1,4,5]]
TÝ37SKδ+€`        # Combine it with every position these 2x2-shapes can be on the 4x4
                  # board:
TÝ                #  Push a list in the range [0,10]
  37SK            #  Remove the 3 and 7: [0,1,2,4,5,6,8,9,10]
δ                 #  Apply double-vectorized
 +                #   Add the values together
  €`              #  Flatten it one level down

```

Try just step 1 online.

Step 2: Get all possible 0..length combinations of these possible shape-positions, and check if they can be combined without overlapping indices:

```
æ                 # Get the powerset of this list of lists shape-indices
 ε                # Foreach over each inner list:
  ˜               #  Flatten it to a single list of indices
   ÐÙQ            #  Check if all indices are unique:
   Ð              #   Triplicate the list of indices
    Ù             #   Uniquify the top copy
     Q            #   Check if the top two lists are still the same

```

Try just the first two steps online.

Step 3: For each valid list of indices, create the board-matrix and output it:

```
      i           #  If the earlier check is truthy:
       X          #   Push a 1
        16Å0      #   Push a list of 16 0s
            r     #   Reverse the stack from indices,1,16x0 to 16x0,1,indices
                  #   (where the indices are from the triplcate of step 2)
             ǝ    #   Insert a 1 into the list of 16 0s at the given indices
              4ô  #   Split the list into parts of size 4
                , #   Pop and output this 4x4 matrix with trailing newline

```
> 2 votes

# Answer
# Charcoal, 47 bytes

```
⊞υ⁵⁴¹²⁰⁰Ｆ¹³Ｆ×Ｘ²ι⟦³⁵¦⁶⁷⟧ＦυＦ¬＆λκ⊞υ⁺λκＥυＥ⪪⍘ι²¦⁵Φλξ

```

Try it online! Link is to verbose version of code. Outputs 215 4×4 grids using `1`s for free and `0`s for occupied cells. Explanation:

```
⊞υ⁵⁴¹²⁰⁰

```

Start with a completely occupied grid. `541200` is `10000100001000010000` in binary, where the `0`s are occupied cells and the `1`s are separators; the grid is obtained by splitting the bits into rows of `5` and then deleting the first column.

```
Ｆ¹³

```

Loop over all valid and some invalid (`3`, `4`, `8` and `9`) shape positions. (Invalid shape positions intersect the separators thus preventing shapes from being removed at those positions.)

```
Ｆ×Ｘ²ι⟦³⁵¦⁶⁷⟧

```

Loop over the bit patterns that represent the two `L` shapes at that position.

```
Ｆυ

```

Loop over the existing boards.

```
Ｆ¬＆λκ⊞υ⁺λκ

```

If the shape can be removed then add the new board.

```
ＥυＥ⪪⍘ι²¦⁵Φλξ

```

Output the discovered boards.
> 1 votes

---
Tags: code-golf, kolmogorov-complexity
---