# Is this number a factorial?

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!

• If the language supports only numbers in the range {0,1}, can I expect the input to always be 1? May 20, 2017 at 9:45
• @eush77 Abusing native number types to trivialize a problem is forbidden by default. May 20, 2017 at 17:56
• is 4! a truthy? May 20, 2017 at 22:04
• Question: Why aren't you using the I/O defaults? May 22, 2017 at 23:15
• @CalculatorFeline Didn't know they existed, if you still want to know the answer :-P Sorry Mar 18, 2021 at 11:14

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

# 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



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, 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



Try it!

# JavaScript (ES6), 71 bytes

This takes in input as function argument and alerts 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 alerted.

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

• Eval might be shorter than using a code block. May 20, 2017 at 15:29
• @Downgoat How should I do that? Sorry if it's too obvious! :P May 21, 2017 at 7:54

# PHP, 32 Bytes

prints -2 for true and -1 for false

for(;1<$argn/=++$x;);echo~$argn;  Try it online! • echo$a&1 would work in PHP too (see my JS answer). May 20, 2017 at 10:26
• @Arnauld the other both bitwise operations should work in JS too May 20, 2017 at 10:36
• Yup. Or even ~$a if -1 / -2 are acceptable outputs. May 20, 2017 at 10:38 • -3 bytes: for(;1<$argn/=++$x;);echo~$argn;. May 20, 2017 at 10:53
• Is -1 really falsy in PHP? (I have never used this language) May 20, 2017 at 12:56

# Charcoal, 24 bytes

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


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

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


## C, 4241 38 bytes

-3 bytes by @KritixiLithos!

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


Try it online!

• Looks like 41 bytes to me ... May 20, 2017 at 22:24
• your TIO link shows a different program than the one in your post, and that one is 39 bytes May 21, 2017 at 1:25
• @HagenvonEitzen fixed May 21, 2017 at 8:13
• @ConorO'Brien fixed May 21, 2017 at 8:13
• -3 bytes by changing m=n==1 to m=n, and then another -3 bytes by using recursion. But you should identify this as "C (gcc)" not just C, because the omit-return hack doesn't work in all C compilers, e.g. clang. Mar 13, 2021 at 11:37

# 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>,
F>>,
A<1>, I<2>>>


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

# 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)
);
}
}


# Ruby, 34 bytes

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


Try it online!

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  • Welcome to PPCG and golfing in Haskell in particular! You can save a byte with f<$>[1..x] instead of map f[1..x]. May 21, 2017 at 8:22

## 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


# 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?


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


# 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()

• you can use 1sX instead of 100p at the beginning as long as you swutch all the other get and put coordinates to 30 instead of 00 to save a byte. May 18, 2018 at 21:45
• @MistahFiggins thanks! May 19, 2018 at 10:12

# 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

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.

• Welcome to PPCG! You might want to add a Try it online! link. Jan 27, 2019 at 9:19
• Jan 27, 2019 at 13:13
• @JonathanFrech Thank you for the improvement, but I'm unsure of how it works exactly, I put some comments to explain what I think it is, could you check if this is it? Also there is one specific thing I don't understand if my rational is correct, which is that you assign a=f(b)-a on the beginning, so how can you call c(a,b+1) without any problems? I would have thought the value of a would be lost after the first iteration Jan 27, 2019 at 14:10
• @FilipeRodrigues To my knowledge, it is simply an undefined behaviour exploitation with regards to gcc on some processors. The registers for the last assigned integer and the integer return value just happen to be the same in some (!) cases. Regarding your question, a= is the very last thing that will happen, so it cannot override c's argument. I actually do not think that there is a sequencing issue of any kind. If you simply add an return a; the a= should simply be an obfuscation. Jan 27, 2019 at 15:01
• For the sake of fairness, I also want to say that @Deadcode provided the TIO link and the test wrapper. Jan 27, 2019 at 15:03

# 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!

• 159 Jan 30, 2019 at 7:23

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

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;}

• I unfortunately think this solution is incorrect. Perhaps there was some confusion regarding integer division? Here is a link to some failing test cases: Try it online!
– dana
Jan 22, 2019 at 13:30
• @dana you're right, I didn't account for m/s being between 1 and 2 and ending up 1 for a non-factorial. Feb 19, 2019 at 15:08

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

• Ah, you can also combine the p and i initialisations to remove a byte
– Jo King
Aug 6, 2019 at 4:11
• Building on @JoKing 44 bytes Sep 27, 2019 at 17:53

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

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

• -2 bytes: lambda n,t=1:n in[t:=t*-~i for i in range(n)] Apr 3, 2022 at 10:46

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 = 
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 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


# 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!

• dip and while are good in production, but they're often losers in code golf. And you can trash the stack and stdout as long as the result is at the top of the stack. I could shorten the * solution to 38 bytes. Mar 19, 2021 at 3:49
• The best I could find for / one is 40 bytes. Also locals is visible by default, so you don't need it in the header. Mar 19, 2021 at 3:50
• @Bubbler Thanks, those are amazing! They're pretty different from mine, though, so do you want to post your own answer?
– user
Mar 19, 2021 at 13:08

# 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

• Because f always returns a boolean, could you just take out the 1> check entirely? Apr 3, 2022 at 11:04
• @dingledooper Ah, I thought that would cause infinite recursion, but I was wrong. Thanks! Apr 3, 2022 at 12:00

## PHP4 (39 chars)

Given $argv as a command line argument, the script will answer to stdout and silence the notice. for($n=$argv;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.

• You'd have to add the #include<stdlib.h> to your score if you want to use errno. However, it's actually shorter to declare and use a new variable: ato.pxeger.com/… Apr 3, 2022 at 12:05
• @pxeger thank you, i updated the code by declaring a new i variable.
– user111777
Apr 3, 2022 at 12:11

# JavaScript (ES6), 60 58 bytes

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


# 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

• this outputs 0 for 2, try adding ) to increase values. This solution used the exact same logic (was basically identical to yours so I won't post it).
– maxb
May 18, 2018 at 18:32

## 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 *'.

# J, 9 bytes

e.!@i.@>:


Try it online!

• 0=1|!^:_1 should be much faster, and can handle huge numbers.
• And 0=1|!inv even saves you a byte... Jan 26, 2019 at 2:40
/.!MS