# 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 '17 at 9:45
• @eush77 Abusing native number types to trivialize a problem is forbidden by default. May 20 '17 at 17:56
• is 4! a truthy? May 20 '17 at 22:04
• Question: Why aren't you using the I/O defaults? May 22 '17 at 23:15
• @CalculatorFeline Didn't know they existed, if you still want to know the answer :-P Sorry Mar 18 '21 at 11:14

# 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 '17 at 15:29
• @Downgoat How should I do that? Sorry if it's too obvious! :P May 21 '17 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 '17 at 10:26
• @Arnauld the other both bitwise operations should work in JS too May 20 '17 at 10:36
• Yup. Or even ~$a if -1 / -2 are acceptable outputs. May 20 '17 at 10:38 • -3 bytes: for(;1<$argn/=++$x;);echo~$argn;. May 20 '17 at 10:53
• Is -1 really falsy in PHP? (I have never used this language) May 20 '17 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 '17 at 22:24
• your TIO link shows a different program than the one in your post, and that one is 39 bytes May 21 '17 at 1:25
• @HagenvonEitzen fixed May 21 '17 at 8:13
• @ConorO'Brien fixed May 21 '17 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 '21 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 '17 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 '18 at 21:45
• @MistahFiggins thanks! May 19 '18 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 '19 at 9:19
• Jan 27 '19 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 '19 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 '19 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 '19 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 '19 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 '19 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 '19 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 '19 at 4:11
• Building on @JoKing 44 bytes Sep 27 '19 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 :)

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

# 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 '21 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 '21 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 '21 at 13:08

# 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 '18 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.
May 22 '17 at 6:35
• @Adám wow, I didn't think in terms of inverse per se. May 22 '17 at 7:14
• And 0=1|!inv even saves you a byte... Jan 26 '19 at 2:40

# Pyth, 5 bytes

/.!MS


• I was about to post... May 20 '17 at 12:37
• @LeakyNun Yeah I felt it. But you posted the Jelly answer I had made... May 20 '17 at 12:39

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

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

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


# Pari/GP, 23 bytes

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


Try it online!