Is this number a factorial?

38

8

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!

Arjun

Posted 2017-05-20T09:19:35.893

Reputation: 4 544

2If the language supports only numbers in the range {0,1}, can I expect the input to always be 1? – eush77 – 2017-05-20T09:45:53.263

11

@eush77 Abusing native number types to trivialize a problem is forbidden by default.

– Dennis – 2017-05-20T17:56:40.623

1is 4! a truthy? – tuskiomi – 2017-05-20T22:04:38.523

Question: Why aren't you using the I/O defaults? – CalculatorFeline – 2017-05-22T23:15:58.563

Answers

37

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.

Fatalize

Posted 2017-05-20T09:19:35.893

Reputation: 32 976

It's perfectly fine to take input via Command Line Arguments. – ATaco – 2017-05-20T09:45:37.447

Why does it output true. and not simply true? – Beta Decay – 2017-05-20T09:45:53.027

6@BetaDecay That's because it's the way it's printed in Prolog (this has to do with the fact that true. is a statement and true is not) – Fatalize – 2017-05-20T09:46:44.623

6It's a trivial solution, but it's clever because of the way prolog works. – Esolanging Fruit – 2017-05-21T06:18:41.543

1I'm not sure which character encoding has in its table of 256 bytes – Nayuki – 2017-05-22T19:43:11.940

Brachylog uses UTF-8 so this is 3 bytes – that other guy – 2017-05-22T19:49:01.753

5

@Nayuki This one, which is custom

– Fatalize – 2017-05-22T21:11:57.857

17First custom languages, then custom encodings... code golf is dead. We've completely subverted the whole point of these fun problems in the first place – Alexander - Reinstate Monica – 2017-05-23T05:57:36.707

15@Alexander Custom encodings are irrelevant to whatever problem you're talking about. I could use any "existing" encoding instead and it would still be 1 byte. It would just be much less readable. – Fatalize – 2017-05-23T06:15:41.663

1Congratulations on winning! :) – Arjun – 2017-05-28T09:24:57.007

19

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

Leaky Nun

Posted 2017-05-20T09:19:35.893

Reputation: 45 011

19

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.

Dennis

Posted 2017-05-20T09:19:35.893

Reputation: 196 637

2Because us code golfers care about efficiency. – Okx – 2017-05-20T15:10:06.283

12It's a dramatic complexity improvement at the cost of one byte and it's a clever use of a built-in if I may say so myself. ¯\(ツ) – Dennis – 2017-05-20T15:16:29.667

Interestingly, this returns true for 0, while @LeakyNun's 3 byte answer, while much slower in general, correctly returns false for 0. Are extra bytes needed to return false for 0 in an efficient-execution-time answer? – Deadcode – 2019-01-31T17:43:46.490

@Deadcode Checking for 0 would require two extra bytes. If not sure if the OP's definition of "natural numbers" includes 0 or not. The test cases don't... – Dennis – 2019-01-31T19:07:03.947

18

ECMAScript Regex, 733+ 690+ 158 119 118 (117) bytes

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 at the very least equal in power to molecular lookahead, but the latter tends to make for more straightforward and elegant implementations.)

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, 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 each time. (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.

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!

Edit: I was able to drop 1 byte (119 → 118) using a trick found by Grimy that can futher shorten division in the case that the quotient is guaranteed to be greater than or equal to the divisor.

With no further ado, here's the regex:

True/false version (118 bytes):

^((x*)x*)(?=\1$)(?=(xxx\2)+$)((?=\2\3*(x(?!\3)xx(x*)))\6(?=\5+$)(?=((x*)(?=\5(\8*$))x)\7*$)x\9(?=x\6\3+$))*\2\3$|^xx?$

Try it online!

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

^(?=((x*)x*)(?=\1$)(?=(xxx\2)+$)((?=\2\3*(x(?!\3)xx(x*)))\6(?=\5+$)(?=((x*)(?=\5(\8*$))x)\7*$)x\9(?=x\6\3+$))*\2\3$)\3|^xx?$

Try it online!

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

^((x*)x*)(?=\1$)(?=(xxx\2)+$)((?=\2\3*(x(?!\3)xx(x*)))\6(?=\5+$)(?=((x*)(?=\5(\8*$))x)\7*$)x\9(?=x\6\3+$))*\2\K\3$|^xx?$

And the free-spaced version with comments:

  ^
  (?=                           # Remove this lookahead and the \3 following it, while
                                # preserving its contents unchanged, to get a 119 byte
                                # regex that only returns match / no-match.
    ((x*)x*)(?=\1$)             # Assert that tail is even; \1 = tail / 2;
                                # \2 = (conjectured N for which tail == N!)-3; tail = \1
    (?=(xxx\2)+$)               # \3 = \2+3 == N; Assert that tail is divisible by \3
    # The loop is seeded: X = \1; I = 3; tail = X + I-3
    (
      (?=\2\3*(x(?!\3)xx(x*)))  # \5 = I; \6 = I-3; Assert that \5 <= \3
      \6                        # tail = X
      (?=\5+$)                  # Assert that tail is divisible by \5
      (?=
        (                       # \7 = tail / \5
          (x*)                  # \8 = \7-1
          (?=\5(\8*$))          # \9 = tool for making tail = \5\8
          x
        )
        \7*$
      )
      x\9                       # Prepare the next iteration of the loop: X = \7; I += 1;
                                # tail = X + I-3
      (?=x\6\3+$)               # Assert that \7 is divisible by \3
    )*
    \2\3$
  )
  \3                            # Return N, the inverse factorial, as a match
|
  ^xx?$                         # Match 1 and 2, which the main algorithm can't handle

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)

Note that ((x*)x*) can be changed to ((x*)+), dropping the size by 1 byte (to 117 bytes) with no loss of correct functionality – but the regex exponentially explodes in slowness. However, this trick, while it works in PCRE and .NET, does not work in ECMAScript, due to its behavior when encountering a zero-length match in a loop. ((x+)+) would work in ECMAScript, but this would break the regex, because for \$n=3!\$, \2 needs to capture a value of \$3-3=0\$ (and changing the regex to be 1-indexed would undo the golf benefit of this).

The .NET regex engine does not emulate this behavior in its ECMAScript mode, and thus the 117 byte regex works:

Try it online! (exponential-slowdown version, with .NET regex engine + ECMAScript emulation)

Deadcode

Posted 2017-05-20T09:19:35.893

Reputation: 3 022

14

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.

Arnauld

Posted 2017-05-20T09:19:35.893

Reputation: 111 334

Nice - really like the use of ~ at the end. – Steve Bennett – 2017-05-21T22:46:25.433

Can you edit so I can undownvote? (If you want to know why I downvoted, it's because I forgot about this question's unusual I/O rules.) – CalculatorFeline – 2017-05-25T01:15:23.057

@Arnauld Undownvoted. – CalculatorFeline – 2017-05-26T21:02:55.200

11

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

Jonathan Allan

Posted 2017-05-20T09:19:35.893

Reputation: 67 804

@ovs we have been restricted to a two consistent outputs. That, unfortunately, returns 1 for all factorials except 1 for which it returns True. – Jonathan Allan – 2017-05-20T10:29:54.293

11

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

Computronium

Posted 2017-05-20T09:19:35.893

Reputation: 151

9

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 1s and a multiple of it many 1s on the bottom line and replace it with

  • 1$1¶$#2$* the top line many 1s 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 1s, 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.

user41805

Posted 2017-05-20T09:19:35.893

Reputation: 16 320

Save a byte by removing the 1 as it is implied when $* is at the end of the replacement. – Neil – 2017-05-20T10:38:28.517

Better still, combine the $* with the other two lines. – Neil – 2017-05-20T10:41:20.247

Try it online! – Neil – 2017-05-20T10:43:48.523

@Neil I was looking for a way to collapse the loop into just one statement, thanks for showing me the way :) – user41805 – 2017-05-20T10:49:22.580

3I'm impressed that you found a way to crash Retina conditionally. :) – Martin Ender – 2017-05-20T16:36:49.037

2Can you add an explanation? – CalculatorFeline – 2017-05-22T23:13:47.113

8

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

Emigna

Posted 2017-05-20T09:19:35.893

Reputation: 50 798

1Wouldn't you need to duplicate the input first because L pops its input? Also, Å! gives you a list of factorial less than or equal to the input. – Neil A. – 2017-05-21T08:33:43.650

@NeilA. Fortunately the input is popped again if there are not enough arguments on the stack for an operation, so I don't need D here. Good catch about Å!. I always forget about the list-commands. It won't save any bytes, but it is more efficient for sure. – Emigna – 2017-05-21T08:37:07.383

I didn't know about input being popped again...that sure could save a lot of bytes. – Neil A. – 2017-05-21T08:42:52.697

@NeilA. It is a fairly new feature. It was added less than a month ago I think. – Emigna – 2017-05-21T08:53:34.913

8

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)

Technocoder

Posted 2017-05-20T09:19:35.893

Reputation: 81

Hi! Welcome to PPCG! Nice first answer! Good luck for the future! – Arjun – 2017-05-20T17:09:21.850

Nice first answer ! You can save a few byte like this: int a(int n){int i=n,j=0;for(;i;)j|=lround(exp(lgamma(i--+1)))==n;return j;}. lround and lgamma are already C++11 so could simply #include<cmath>. Maybe you can even further improve my suggestions :) – Christoph – 2017-05-22T09:04:23.877

7

Haskell, 43 26 bytes

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

Try it online!

  • Saved 17 bytes, thanks to Laikoni

sudee

Posted 2017-05-20T09:19:35.893

Reputation: 551

2f n=elem n$scanl1(*)[1..n] is ridiculous inefficient but shorter. – Laikoni – 2017-05-20T11:17:16.897

Isn't there some rule about code efficiency? – sudee – 2017-05-20T12:15:18.480

1None that I am aware of. [tag:code-golf] asks for a solution in as few bytes as possible without any efficiency statements. Also on my machine the function works up to 40430 without noticeable delay. – Laikoni – 2017-05-20T12:44:27.257

I meant something along the lines of "the solution should terminate within a reasonable timeframe", but I guess it fits the requirements either way. Thanks! – sudee – 2017-05-20T16:24:41.630

1Nice and simple. I thought I could do better with division—say, divMod by [1..] successively until reaching a zero remainder with a quotient of 1 (factorial) or a nonzero remainder (non-factorial), but it doesn’t seem to be the right approach. I did find this cute 46-character solution, though: f|let x%n=mod n x==0&&(x+1)%div n x||n==1=(1%). – Jon Purdy – 2017-05-23T02:48:31.640

Check out Laikoni's answer for division based approach.

– sudee – 2017-05-23T14:01:13.210

6

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.

Laikoni

Posted 2017-05-20T09:19:35.893

Reputation: 23 676

5

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

Beta Decay

Posted 2017-05-20T09:19:35.893

Reputation: 21 478

5

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

Luke

Posted 2017-05-20T09:19:35.893

Reputation: 4 675

1I really should add a "contains" built-in :P – ETHproductions – 2017-05-20T11:14:25.627

1Oh hey, you could change aU ¦J to x¥U (map each X to X==U and sum), though it won't work on TIO. – ETHproductions – 2017-05-20T11:16:00.953

Fails for 2 becuase o will only give you [0,1]. Here's a fix with a 1 byte saving.

– Shaggy – 2017-09-26T14:51:31.093

5

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

Luis Mendo

Posted 2017-05-20T09:19:35.893

Reputation: 87 464

4

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.

faubi

Posted 2017-05-20T09:19:35.893

Reputation: 2 599

-5 bytes TIO

– Nahuel Fouilleul – 2019-01-22T11:14:27.640

4

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
}

Brad Gilbert b2gills

Posted 2017-05-20T09:19:35.893

Reputation: 12 713

17 bytes: {$_∈[\*] 1..$_}. Another interesting approach is 2>*.polymod(1..*).sum. – nwellnhof – 2018-11-11T12:36:02.353

4

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.

Hagen von Eitzen

Posted 2017-05-20T09:19:35.893

Reputation: 371

Try it online! – Deadcode – 2019-01-27T17:57:32.263

Can be dropped to 32 bytes: Try it online! or 31 bytes by returning nonzero for false: Try it online!

– Deadcode – 2019-01-27T18:44:44.333

4

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)

BlueWizard

Posted 2017-05-20T09:19:35.893

Reputation: 161

4

R, 28 22 bytes

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

Try it online!

ngm

Posted 2017-05-20T09:19:35.893

Reputation: 3 974

Make it a 22 bytes full program?

– JayCe – 2018-05-21T01:46:20.773

1I'm worried I'll start using this stuff in production code. – ngm – 2018-05-22T17:03:41.380

4

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!

dana

Posted 2017-05-20T09:19:35.893

Reputation: 2 541

2The && can be golfed to &, and the trailing ; doesn't have to be counted for lambda functions. Also, can't the ulong k=2 be uint k=2 in your 50-byte answer? – Kevin Cruijssen – 2019-01-22T12:40:26.407

1Good catch on the & vs &&. I thought I was getting a stack overflow, but it seems to work afterall. ulong is 64 bits while uint is 32. It looks like others are using int so maybe I'll just use that for the short version. With regards to the trailing ;, these are full functions, not lambdas, so I think I need include them? – dana – 2019-01-22T12:56:14.623

That's really strange how .NET can resolve / and % between ulong and uint, but not ulong and int. Didn't know that :) – dana – 2019-01-22T13:13:35.250

1

@Oliver - With double you start to see rounding at some point - for example, 24! and 120! fail. While System.Numerics.BigInteger has the most precision, int is the shortest answer :)

– dana – 2019-01-22T19:28:44.610

It should be noted that this returns the wrong result for zero. And @KevinCruijssen's golfing of && to & results in a slowdown very similar to the golfing of || to | in my C++ answer (they both work in C++ and the former is only 3% slower), but of course the latter won't work in C# due its strict separation of boolean and integer types. In any case, I like that one of the versions handles very big numbers. – Deadcode – 2019-01-31T05:20:00.023

1@Deadcode - You are right about 0 :) Based on the examples in the challenge, I interpreted "natural numbers" to mean 1,2,... I agree that in the real world, it is better to use the short circuiting && operator. But this is code golf ;) Glad you like the 10000! example! – dana – 2019-01-31T14:21:34.757

4

C++ (clang), 51 bytes

Recursion wins out as far as golfing goes.

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!

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!

Deadcode

Posted 2017-05-20T09:19:35.893

Reputation: 3 022

50 EDIT: 49, without recursion. – Grimmy – 2019-05-03T16:31:49.297

Back to recursion for 48. And you probably won’t like this, but 44 by using a global var.

– Grimmy – 2019-05-03T17:25:39.733

3

Mathematica, 20 bytes

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

other version to test big numbers (see comments)

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

tests up to 1000!

J42161217

Posted 2017-05-20T09:19:35.893

Reputation: 15 931

2As I understand the question, if Mathematica is capable of taking 1001! as an input then this doesn't meet the spec. – Peter Taylor – 2017-05-20T10:26:21.887

2You could even save three bytes while making it valid for all inputs. Just replace 10^3 with # ; you could save another byte with using Range@# – Julien Kluge – 2017-05-20T11:06:38.400

@Julien Klugethen searching for 1243234 would take forever... – J42161217 – 2017-05-20T12:47:21.370

@Peter Taylor why would you ask if 1001! is factorial? ;-) – J42161217 – 2017-05-20T13:14:23.530

Why would you not? – Peter Taylor – 2017-05-20T14:11:43.383

@Jenny_mathy but this is not relevant. The challenge didn't gave any performance restrictions. Theoretically it works like charm. It just takes a long time and it saves bytes so why don't? – Julien Kluge – 2017-05-20T16:52:45.493

ok...done......... – J42161217 – 2017-05-20T17:08:12.853

1I think you can save another byte by replacing Range[#] with Range@# :) – numbermaniac – 2017-05-21T01:45:18.847

3Looks like you can save yet another byte with infix syntax: !Range@#!~FreeQ~#&. – numbermaniac – 2017-05-21T02:06:20.180

Equally short: MemberQ[Range[#]!, #] & – David G. Stork – 2019-01-22T06:13:38.023

More computationally efficient, but also longer: (a = Range[#]!) \[Union] {#} == a & where \[Union] should be counted as a single byte. – David G. Stork – 2019-01-22T06:23:07.177

3

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!

Neim, 3 bytes (non-competing)

Non-competing as the contains token and factorial token were added after the challenge was made.


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!

Okx

Posted 2017-05-20T09:19:35.893

Reputation: 15 025

3

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?

user41805

Posted 2017-05-20T09:19:35.893

Reputation: 16 320

Cumulative sum? – Leaky Nun – 2017-05-20T12:32:07.710

@LeakyNun Fixed – user41805 – 2017-05-20T12:32:58.810

One extra byte in GNU APL 1.2 N∊×\⍳N←⎕ How does this take an argument? I don't see n anywhere. Is this a Dyalog-specific thing? – Arc676 – 2017-05-21T02:15:05.963

2@Arc676 My solution is a train and you call it like so: (⊢∊(×/⍳)) right_argument as you can see in the TIO link. And the refers to the right argument. – user41805 – 2017-05-21T07:57:33.893

Notes: AGL will save you a byte; ⊢∊×\ä⍳. The "correct" (but longer) solution would be 0=1|!⍣¯1; "Is the inverse factorial an integer?" – Adám – 2017-05-22T06:02:13.937

I think ×\ can be !. – Erik the Outgolfer – 2019-01-23T21:39:51.840

@EriktheOutgolfer How didn't anyone think of that. It is pretty obvious! – Adám – 2019-01-25T07:12:55.010

@EriktheOutgolfer Thanks, updated. – user41805 – 2019-07-16T14:47:12.223

3

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

Not a tree

Posted 2017-05-20T09:19:35.893

Reputation: 3 106

You could transform you v>\n<^ into \\n/ ; see here

– Aaron – 2017-05-22T15:53:03.820

@Aaron, that's brilliant, thank you! – Not a tree – 2017-05-23T01:11:15.353

3

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, Input, 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, Output, and exit. If it's negative, we've gone too far, so we push 0, Output, 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.

user48543

Posted 2017-05-20T09:19:35.893

Reputation:

2

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)

Arjun

Posted 2017-05-20T09:19:35.893

Reputation: 4 544

Eval might be shorter than using a code block. – Downgoat – 2017-05-20T15:29:21.280

@Downgoat How should I do that? Sorry if it's too obvious! :P – Arjun – 2017-05-21T07:54:50.497

2

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

Roman Gräf

Posted 2017-05-20T09:19:35.893

Reputation: 2 915

2

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.

steenbergh

Posted 2017-05-20T09:19:35.893

Reputation: 7 772

2

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

Prime

Posted 2017-05-20T09:19:35.893

Reputation: 121

Welcome to PPCG and golfing in Haskell in particular! You can save a byte with f<$>[1..x] instead of map f[1..x]. – Laikoni – 2017-05-21T08:22:24.107

2

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

phroureo

Posted 2017-05-20T09:19:35.893

Reputation: 183

2

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?

mudkip201

Posted 2017-05-20T09:19:35.893

Reputation: 833

2

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.

Filipe Rodrigues

Posted 2017-05-20T09:19:35.893

Reputation: 121

2

Welcome to PPCG! You might want to add a Try it online! link.

– Deadcode – 2019-01-27T09:19:49.390

77 bytes. – Jonathan Frech – 2019-01-27T13:13:31.393

@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 – Filipe Rodrigues – 2019-01-27T14:10:01.877

@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. – Jonathan Frech – 2019-01-27T15:01:09.303

For the sake of fairness, I also want to say that @Deadcode provided the TIO link and the test wrapper. – Jonathan Frech – 2019-01-27T15:03:11.617

1

JavaScript (ES6), 60 58 bytes

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

Luke

Posted 2017-05-20T09:19:35.893

Reputation: 4 675

1

PHP, 32 Bytes

prints -2 for true and -1 for false

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

Try it online!

Jörg Hülsermann

Posted 2017-05-20T09:19:35.893

Reputation: 13 026

1echo$a&1 would work in PHP too (see my JS answer). – Arnauld – 2017-05-20T10:26:47.690

@Arnauld the other both bitwise operations should work in JS too – Jörg Hülsermann – 2017-05-20T10:36:35.680

1Yup. Or even ~$a if -1 / -2 are acceptable outputs. – Arnauld – 2017-05-20T10:38:07.560

1-3 bytes: for(;1<$argn/=++$x;);echo~$argn;. – user63956 – 2017-05-20T10:53:07.947

Is -1 really falsy in PHP? (I have never used this language) – Luis Mendo – 2017-05-20T12:56:00.197

@LuisMendo NO but we can take any values so long they are consistent to all inputs. It saves 1 Byte see the history. Here are a list which values are really false in PHP http://php.net/manual/en/types.comparisons.php

– Jörg Hülsermann – 2017-05-20T13:10:14.463

I understood the challenge as requiring a truthy and a falsy value, but you may be right in assuming that any two distinct values will do – Luis Mendo – 2017-05-20T15:02:45.233

@LuisMendo If I am not right I can do a rollback to the previous version. – Jörg Hülsermann – 2017-05-20T15:07:16.570

@JörgHülsermann Maybe ask the OP? – Luis Mendo – 2017-05-20T15:17:02.220

1

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

FrodCube

Posted 2017-05-20T09:19:35.893

Reputation: 539

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 – 2018-05-18T18:32:02.703

1

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

NikoNyrh

Posted 2017-05-20T09:19:35.893

Reputation: 2 361

1

J, 9 bytes

e.!@i.@>:

Try it online!

Leaky Nun

Posted 2017-05-20T09:19:35.893

Reputation: 45 011

20=1|!^:_1 should be much faster, and can handle huge numbers. – Adám – 2017-05-22T06:35:40.843

@Adám wow, I didn't think in terms of inverse per se. – Leaky Nun – 2017-05-22T07:14:17.437

And 0=1|!inv even saves you a byte... – Jonah – 2019-01-26T02:40:04.977

1

Pyth, 5 bytes

/.!MS

online interpreter link

Erik the Outgolfer

Posted 2017-05-20T09:19:35.893

Reputation: 38 134

I was about to post... – Leaky Nun – 2017-05-20T12:37:24.673

1@LeakyNun Yeah I felt it. But you posted the Jelly answer I had made... – Erik the Outgolfer – 2017-05-20T12:39:51.143

1

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!

Mr. Xcoder

Posted 2017-05-20T09:19:35.893

Reputation: 39 774

1

Charcoal, 24 bytes

NβA⟦⟧γW¬﹪βL⊞OγβA÷βLγβ⁼β¹

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

Neil

Posted 2017-05-20T09:19:35.893

Reputation: 95 035

1

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.

Horváth Dávid

Posted 2017-05-20T09:19:35.893

Reputation: 679

1

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

MetaColon

Posted 2017-05-20T09:19:35.893

Reputation: 391

Can save three bytes: true -> 1>0, false -> 1<0. – ProgramFOX – 2017-05-20T15:17:13.297

@ProgramFOX I got an even better idea - but thank you. – MetaColon – 2017-05-20T16:52:46.370

Ah, yeah, that's better :) – ProgramFOX – 2017-05-20T17:15:02.517

1How about n=>int l=1,i=1,r=0;for(;i<13;i++)if((l*=i)==n)r=1;return r;} – Arjun – 2017-05-21T15:35:51.533

I don't know C# but can't you use the Ternary operator? r=(l*=i)==n?1:0 instead of if – Arjun – 2017-05-21T15:37:26.110

@Arjun this won't work, as it will overwrite the 1 that may be saved in it. – MetaColon – 2017-05-21T15:39:57.470

1r=(l*=i)==n?1:r – Arjun – 2017-05-21T15:41:02.210

Now, you, too, are ahead of my JavaScript answer, which will always be stuck on 0 score. :-\

– Arjun – 2017-05-21T15:51:21.733

1

C, 42 41 38 bytes

-3 bytes by @KritixiLithos!

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

Try it online!

betseg

Posted 2017-05-20T09:19:35.893

Reputation: 8 493

1Looks like 41 bytes to me ... – Hagen von Eitzen – 2017-05-20T22:24:46.980

your TIO link shows a different program than the one in your post, and that one is 39 bytes – Conor O'Brien – 2017-05-21T01:25:02.577

@HagenvonEitzen fixed – betseg – 2017-05-21T08:13:01.990

@ConorO'Brien fixed – betseg – 2017-05-21T08:13:09.370

1

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

algmyr

Posted 2017-05-20T09:19:35.893

Reputation: 858

1

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

eush77

Posted 2017-05-20T09:19:35.893

Reputation: 1 280

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. – MildlyMilquetoast – 2018-05-18T21:45:19.413

@MistahFiggins thanks! – eush77 – 2018-05-19T10:12:35.227

1

Pari/GP, 23 bytes

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

Try it online!

alephalpha

Posted 2017-05-20T09:19:35.893

Reputation: 23 988

1

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.

eush77

Posted 2017-05-20T09:19:35.893

Reputation: 1 280

1

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

pizzapants184

Posted 2017-05-20T09:19:35.893

Reputation: 3 174

1

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?

Mego

Posted 2017-05-20T09:19:35.893

Reputation: 32 998

1

Ruby, 34 bytes

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

Try it online!

G B

Posted 2017-05-20T09:19:35.893

Reputation: 11 099

1

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!

Arjun

Posted 2017-05-20T09:19:35.893

Reputation: 4 544

1Welcome​ to Japt :) You can save a couple of bytes on this by dropping the first U (it's implicit in this instance) and by using the ¥ shortcut for == (or the shortcut for ===). – Shaggy – 2017-05-23T17:49:12.513

1

Japt, 4 bytes

õÊøU

Try it online!

Oliver

Posted 2017-05-20T09:19:35.893

Reputation: 7 160

1

Retina, 31 bytes

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

Try it online!


Takes as input a unary number with _ as tally mark

TwiNight

Posted 2017-05-20T09:19:35.893

Reputation: 4 187

1

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)

12Me21

Posted 2017-05-20T09:19:35.893

Reputation: 6 110

1

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.

Ciaran_McCarthy

Posted 2017-05-20T09:19:35.893

Reputation: 689

Can be refactored with a fold and a lambda to save 16 bytes: fun a->Seq.map(fun b->Seq.fold(*)1[2..b]){0..a}|>Seq.contains a – LSM07 – 2019-01-22T04:56:30.290

1

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

Jackson

Posted 2017-05-20T09:19:35.893

Reputation: 101

1

Common Lisp, 56 bytes

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

Try it online

Renzo

Posted 2017-05-20T09:19:35.893

Reputation: 2 260

1

Brain-Flak, 154 bytes

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

Try it online!

MegaTom

Posted 2017-05-20T09:19:35.893

Reputation: 3 787

1

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!

ბიმო

Posted 2017-05-20T09:19:35.893

Reputation: 15 345

159 – ASCII-only – 2019-01-30T07:23:09.687

1

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!

gggg

Posted 2017-05-20T09:19:35.893

Reputation: 1 715

1

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.

T. Salim

Posted 2017-05-20T09:19:35.893

Reputation: 575

Ah, you can also combine the p and i initialisations to remove a byte – Jo King – 2019-08-06T04:11:03.380

Building on @JoKing 44 bytes

– ceilingcat – 2019-09-27T17:53:57.653

0

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

Ceshion

Posted 2017-05-20T09:19:35.893

Reputation: 201

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 – 2019-01-22T13:30:34.653

@dana you're right, I didn't account for m/s being between 1 and 2 and ending up 1 for a non-factorial. – Ceshion – 2019-02-19T15:08:00.473

0

Ruby, 39 bytes

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

marmeladze

Posted 2017-05-20T09:19:35.893

Reputation: 227

0

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!

Sean

Posted 2017-05-20T09:19:35.893

Reputation: 4 136

0

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

Skidsdev

Posted 2017-05-20T09:19:35.893

Reputation: 9 656

0

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

RosLuP

Posted 2017-05-20T09:19:35.893

Reputation: 3 036

0

Tcl, 71 bytes

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

Try it online!

sergiol

Posted 2017-05-20T09:19:35.893

Reputation: 3 055

Note: $argv is the variable that carries the argument from console; I had just overridden it to test all test cases at once! – sergiol – 2017-09-23T01:45:11.203

0

Tcl, 69 bytes

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

Try it online!

sergiol

Posted 2017-05-20T09:19:35.893

Reputation: 3 055

Now as a function it renders 2 bytes less! – sergiol – 2017-09-23T01:57:38.147

0

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.

DLosc

Posted 2017-05-20T09:19:35.893

Reputation: 21 213

0

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.

LyricLy

Posted 2017-05-20T09:19:35.893

Reputation: 3 313

Is there a point to using strings and then evaling it instead of just using a separate variable to keep track of the number? e.g. 46 bytes

– Jo King – 2019-01-22T05:30:28.440

0

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.

Ben

Posted 2017-05-20T09:19:35.893

Reputation: 109

Output is allowed as return values, which could save you a lot of bytes. – Nissa – 2018-05-18T16:26:06.623

0

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

reffu

Posted 2017-05-20T09:19:35.893

Reputation: 1 361

0

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.

maxb

Posted 2017-05-20T09:19:35.893

Reputation: 5 754

0

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

Conor O'Brien

Posted 2017-05-20T09:19:35.893

Reputation: 36 228

0

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

user85052

Posted 2017-05-20T09:19:35.893

Reputation:

0

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

DeathIncarnate

Posted 2017-05-20T09:19:35.893

Reputation: 916

0

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.

DeathIncarnate

Posted 2017-05-20T09:19:35.893

Reputation: 916

0

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.

Tau

Posted 2017-05-20T09:19:35.893

Reputation: 1 935