18
votes
\$\begingroup\$

The challenge:

Write a program or a function that inputs a positive number and returns its factorial.

Note: This is a question. Please do not take the question and/or answers seriously. More information here. Every question is also a question, so the highest voted answer wins.

\$\endgroup\$
4
  • 6
    \$\begingroup\$ See also The Evolution of Haskell programmer. \$\endgroup\$
    – Petr
    Dec 29, 2013 at 7:46
  • 4
    \$\begingroup\$ -1, sorry, because we're getting a huge flood of these code trolling questions and this does not really add anything new to them \$\endgroup\$
    – Doorknob
    Dec 29, 2013 at 11:25
  • \$\begingroup\$ Related: codegolf.stackexchange.com/questions/1635/forking-factorials \$\endgroup\$
    – Paul
    Dec 30, 2013 at 10:08
  • \$\begingroup\$ Code-trolling is in the process of being removed, as per the official stance. This question has a fair amount of votes with many answers, many of which are extremely highly voted. It recieved just over 50% "delete" votes on the poll, but it is unique in that it recieved so many answers and votes, so I am locking it for historical significance. \$\endgroup\$
    – Doorknob
    May 12, 2014 at 0:13

61 Answers 61

1
vote
\$\begingroup\$

Haskell

c :: Integer -> (Integer -> Integer) -> Integer -> Integer
c 0 f x = x
c 1 f x = f x
c n f x = f (c (n-1) f x)

factorial 0 = 1
factorial n = (foldl1 (.) $ map c [1..n]) (+1) 0
\$\endgroup\$
0
votes
\$\begingroup\$

C

#include<stdio.h>
int main()
{
    int t;
    int a[200]; //array will have the capacity to store 200 digits.
    int n,i,j,temp,m,x;

    scanf("%d",&t);
    while(t--)
    {
       scanf("%d",&n);
       a[0]=1;  //initializes array with only 1 digit, the digit 1.
       m=1;    // initializes digit counter

       temp = 0; //Initializes carry variable to 0.
       for(i=1;i<=n;i++)
       {
            for(j=0;j<m;j++)
            {
               x = a[j]*i+temp; //x contains the digit by digit product
               a[j]=x%10; //Contains the digit to store in position j
               temp = x/10; //Contains the carry value that will be stored on later indexes
            }
             while(temp>0) //while loop that will store the carry value on array.
             { 
               a[m]=temp%10;
               temp = temp/10;
               m++; // increments digit counter
             }
      }
              for(i=m-1;i>=0;i--) //printing answer
              printf("%d",a[i]);
              printf("\n");
    }
    return 0;
}
\$\endgroup\$
0
votes
\$\begingroup\$

It is well known in combinatorics that

n! (def)= nPr(n,n)

That is, factorial is the number of n-long strings that can be made from n distinct values without repetition.

Here's the faster application of that:

C99

int find_permutations( int n, char* s )
{
    /* find the NUL byte which terminates every string */
    char* p = s;
    while (*(p++));

    int permutations_found = 1;
    if (p > s + n) {
        for( char *f = s; *f; ++f )
            for( char *g = s; g < f; ++g )
                permutations_found *= -(s - p - n) * (*f - *g) / (p - s);
        return! !permutations_found;
    }

    *p = p[-1];
    p[-1] = '0';
    do { permutations_found += find_permutations(n, s); } while (++((-1)[p]) != '0' + n);
    p[-1] = 0;

    return-- permutations_found;
}

int factorial( int n )
{
    char s[n+3];
    s[1] = 0;
    return find_permutations(n, s+1);
}

The slower version would of course generate permutations using rand() and count the unique ones.

\$\endgroup\$
2
  • \$\begingroup\$ Ok, now it works. ideone.com/NV4xyv \$\endgroup\$
    – Ben Voigt
    Dec 31, 2013 at 4:08
  • \$\begingroup\$ The trolliness derives from generating all N*N strings of length N *with repetition, then finding duplicate digits by comparing all pairs. Total runtime: O(N**(N+2)). Then there's the general obfuscation such as use of the return! and return-- statements, using multiplication to set the return value to zero when duplication is detected, and gratuitous use of a VLA. And all without using a single library function. Let's not forget lots and lots of pointers, all with a purpose. \$\endgroup\$
    – Ben Voigt
    Dec 31, 2013 at 4:10
0
votes
\$\begingroup\$

So, clearly we have an interesting math problem here... I would say that the best that we can do is to write a C# program to generate a latex snippet that we can put into a latex document.

class LatexFactorial
{
    public static string getLatexFactorial(int n)
    {
        string latex = n + "! = ";

        for (int i = n; i > 0; i--)
        {
            latex += i + " \\cdot ";
        }

        //Don't forget 0!
        latex += "1";

        return latex;
    }

}

Naturally, the user needs to identify n, but we don't want to make it too easy for the user... we'll use something like this...

 static void Main(string[] args)
    {
        string line = Console.ReadLine();

        Console.WriteLine();
        Console.WriteLine();

        Console.WriteLine(LatexFactorial.getLatexFactorial(int.Parse(line)));

        Console.Read();

    }
\$\endgroup\$
0
votes
\$\begingroup\$

R

You could use factorial but to save some of the precious computing time, just add one to your argument and use the gamma distribution:

gamma(5) # return factorial of 4

Unfortunately, the problem with this approach is that it will return Inf for numbers greater than 170.

> gamma(171)
[1] 7.257416e+306
> gamma(172)
[1] Inf
Warning message:
value out of range in 'gammafn' 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think you mess up together the "gamma distribution and the "gamma function" ;) \$\endgroup\$
    – yo'
    Jan 14, 2014 at 0:40
0
votes
\$\begingroup\$

C#

using System.Numerics;
public static BigInteger GetFactorialRecursive(uint n)
{
  if (n == 0)
  {
     return 1;
  }
  return GetFactorialRecursive(n-1)*n;
}
\$\endgroup\$
0
votes
\$\begingroup\$

TI-Basic

:Lbl Lbl
:Goto Goto
:Lbl Goto
:Lbl Lbl
:if{banana_cream_pie\\0}:Input Label
:for{l&0~~L!->O}
:junky_cream_pie|Disposition Laregely_bloated
:___Endeavoring: the act of eating___
:By the way, if you haven't figured it out yet, the program's already finished
:Typing in the rest of this junk is really only a pain and you might want to stop...
:By the way, here's a GolfScript solution (not by me of course) .!+,1\{)}%{*}/
\$\endgroup\$
0
votes
\$\begingroup\$

dc

echo 10 | dc -e "?[d1-d1<F*]dsFxp"
\$\endgroup\$
0
votes
\$\begingroup\$

C

Sweet and simple.

#include <math.h>
#define factorial(n) tgamma((n)+1)
\$\endgroup\$
1
  • \$\begingroup\$ But I see now that it is equivalent to an R answer given earlier. \$\endgroup\$ Jan 3, 2014 at 23:14
0
votes
\$\begingroup\$

C with threads

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

double f = 1;

pthread_mutex_t mutex_f = PTHREAD_MUTEX_INITIALIZER;;

void *mult_by(void *k) {
  pthread_mutex_lock(&mutex_f);
  f *= *(int*)k;
  pthread_mutex_unlock(&mutex_f);
  return(NULL);
}

int main (int argc, char **argv) {
  int i, n, *k;
  pthread_t *pid;
  void *junk;

  if (argc!=2) exit(1);
  n = atoi(argv[1]);
  pid = malloc(sizeof(pthread_t*)*n);
  k = malloc(sizeof(int*)*n);
  for (i=0; i<n; i++) k[i] = i+1;
  for (i=0;i<n;i++) pthread_create(pid+i, NULL, mult_by, k+i);
  for (i=0;i<n;i++) pthread_join(pid[i], &junk);
  printf("%g\n",f);
  exit(0);
}
\$\endgroup\$
0
votes
\$\begingroup\$

C++

Very elegant solution using modern C++ features:

#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>

using namespace std;

int main() {
        int n;
        cout << "n=";
        cin >> n;
        list<int> l(n);
        iota(l.begin(), l.end(), 0);
        int f = 1;
        while (next_permutation(l.begin(), l.end())) f++;
        cout << f << endl;
}

This generates all the permutations of a linked list of size n, and counts then one by one. Gets pretty slow after n=10. Compile with g++ -std=c++0x.

\$\endgroup\$
0
votes
\$\begingroup\$

Java 1.5+

The algorithm SplitRecursive, because it is simple and the fastest algorithm which does not use prime factorization. Based on http://www.luschny.de/math/factorial/java/FactorialSplit.java.html but only with the standard library. Works great.

import java.math.BigInteger;

public final class FactorialSplit
{
  private long m_nCurrentN;

  FactorialSplit () {}

  private BigInteger _getProduct (final int n)
  {
    final int m = n / 2;
    if (m == 0)
    {
      m_nCurrentN += 2;
      return BigInteger.valueOf (m_nCurrentN);
    }
    if (n == 2)
    {
      m_nCurrentN += 2;
      final long n1 = m_nCurrentN;
      m_nCurrentN += 2;
      final long n2 = m_nCurrentN;
      return BigInteger.valueOf (n1 * n2);
    }
    return _getProduct (n - m).multiply (_getProduct (m));
  }

  public BigInteger getFactorial (final int n)
  {
    if (n < 0)
      throw new IllegalArgumentException ("n >= 0 required, but was " + n);
    if (n < 2)
      return BigInteger.ONE;
    BigInteger aP = BigInteger.ONE;
    BigInteger aR = BigInteger.ONE;
    m_nCurrentN = 1;
    int nH = 0;
    int nShift = 0;
    int nHigh = 1;
    int nLog2n = true ? 31 - Integer.numberOfLeadingZeros (n) : (int) Math.floor (Math.log (n) / Math.log (2));
    while (nH != n)
    {
      nShift += nH;
      nH = n >> nLog2n--;
      int nLen = nHigh;
      nHigh = (nH - 1) | 1;
      nLen = (nHigh - nLen) / 2;
      if (nLen > 0)
      {
        aP = aP.multiply (_getProduct (nLen));
        aR = aR.multiply (aP);
      }
    }
    return aR.shiftLeft (nShift);
  }

  public static BigInteger getAnyFactorialLinear (final int n)
  {
    return new FactorialSplit ().getFactorial (n);
  }
}
\$\endgroup\$
0
votes
\$\begingroup\$

Here is the naive solution in bash:

read INPUT && seq 1 $INPUT > /tmp/numbers && T=1
while read X; do T=$((T*X)); done < /tmp/numbers && echo "$T"

However you should not use this because the arithmetic module in bash cannot count above 9223372036854775807. Instead you should use a character-based approach:

set +e
read INPUT && echo > /tmp/fac &&
seq 1 $INPUT | while read M
do for X in `seq 1 $M`; do cat /tmp/fac >> /tmp/fac2; done &&
mv -f /tmp/fac2 /tmp/fac; done &&
wc -c /tmp/fac

This will work for much larger numbers, provided you have space in /tmp.

In the above, set +e is the code for "don't stop" and && encourages the interpreter to "keep going".

\$\endgroup\$
0
votes
\$\begingroup\$

Python

Everyone knows the key to success in these tasks is to uses built ins in the language, which is why I'm using the Python built in itertools to get the permutations of an array to calculate the factorial.

import itertools

def factorial(n):
    f = [1 for i in itertools.permutations(range(n))]
    return sum(f)
\$\endgroup\$
0
votes
\$\begingroup\$

Mathematica, 21 characters

enter image description here

Or longhand :-

f[n_] := Integrate[t^n/((-1)^-(Sqrt[-1]/Pi))^t, {t, 0, Infinity}]

f[5]

120

How this works: clue

\$\endgroup\$
0
votes
\$\begingroup\$

Powershell

# This line will make sure there aren't any errors in your script.
# You should use this at the start of every script.
$ErrorActionPreference = 'SilentlyContinue'

<#
The next line looks really tricky, but it's actually pretty simple.
    $n= tells the computer we want to give it a number.
    read-host takes that number from us.
    $m= tells the computer we're going to do maths on that number.
    1e3* tells the computer we expect the result to be no longer than 3 digits.
        If the result might be longer than 3 digits you'll need to increase this by changing the 3 to however many digits there might be. Otherwise the answer will be wrong.
    ..1 tells the computer we want accuracy down to the ones digit.
    |%{ starts a maths statement.
#>

($m=1e3*($n=read-host))..1|%{

<#
    This line is a little simpler.
        ($x=1) starts a maths counter at 1. This is needed because computers normally start counting at zero.
        ..$_ brings in the accuracy setting we used earlier.
        |%{ starts a nested maths statement.
#>

    ($x=1)..$_|%{

        # The next bit is really entry-level stuff. You should probably re-read a few chapters if you don't get it.
        # $x gets our starting counter we made.
        # *= tells the computer we want a factorial.
        # $_ pulls in the user input we got earlier.

        $x*=$_

    # This ends the nested maths statement.
    }

    # This next line outputs the maths result in the advanced "X2" format.
    # Trust me, your professor will be very impressed by this.

    "{0:X2}"-f$x

# This ends the rest of the script.
}

Trolls

The above is a fully commented script seeking to appear well-documented and thoroughly explained. However, not a single bit of the documentation is true. Particular items of interest are noted below.

  • Setting $ErrorActionPreference to 'SilentlyContinue' doesn't prevent any errors - it just makes sure they're not displayed. This will also make troubleshooting the script more difficult. Also, the recommendation to use this in all other scripts may make troubleshooting of future scripts more difficult.
  • Changing the 3 to any other number doesn't change the accuracy of the output. It just affects how long the script might run, and how much additional garbage output there might be.
  • There is no "advanced X2 format". The given line changes the output to hexadecimal, with a minimum of 2 digits.

The requested factorial is given in the output. However, the output also includes all other factorials from 1! to ($n*1000)!. Oh, and they're all in hex. Ah, and limited to the maximum value available in a signed 32-bit integer. And since the script starts with ($n*1000)!, it's going to take awhile to run before it outputs any numbers (the majority of the factorials will silently error since they're too large and we set $ErrorActionPreference to 'SilentlyContinue') let alone the right number.

The right answer actually is in there, but someone who doesn't know what they're doing - and especially someone who actually believes the comments - could have a hard time finding it. The simplest way to really do it is:

($x=1)..(read-host)|%{$x*=$_};$x

Granted, that's still limited to the space in a signed 32-bit integer. (The default integer type in PowerShell) But it's a legitimate start.

\$\endgroup\$
0
votes
\$\begingroup\$

JavaScript

We don't want to burden the computer with such a cumbersome operation as multiplication, especially in an interpreted language such as JavaScript, so let's take it easy on it and use addition instead. Or better yet, let's decrease the burden even further by using just subtraction. At least that is better to keep track of, just using one operation instead of who knows how many.

function factorial(n) {
  var m = 1, sum = 0, count = 1;
  if (n == 0 || n == 1) return 1; // We can't forget that 0!=1!=1
  while (m != n) {
    while (count != m) {
      sum = add(sum, add(sum, m);
      count = add(count, 1);
    }
    m = add(m, 1);
  }
  return sum;
}

function add(a, b) {
  var guess = Math.round(Math.tan(Math.random() + .5)));
  /* C'mon, the computer has to take a shot in the dark first. Let it! */

  while (guess - a > b) {
    guess-- // Now let it get a little closer
  }
  return guess; // Now it should be just about right.
}

Did I forget to mention that speed isn't everything? Resources are far more important than speed.


For you all wanting a true list of trolls, here it is:

  1. Takes an extremely long time (I'm not too familiar with Big-O notation, but if you somehow manage to calculate this mess, feel free to make an edit and tack it on here).
  2. Lots (and lots (and lots)) of recursion without the use of for loops.
  3. Almost instant correct answer for 0 (I know it isn't positive, but it's easy) and 1, but gets extremely sluggish quickly.
  4. Prepare for CPU suicide. (It is at least light on RAM...if that counts for anything...)
  5. That add() function is practically useless in all accounts, and only insults the injury for an already tedious function (no multiplication gets enormous, even with standard addition). That 'helper' function already takes O(N) time depending on the guess when it actually works (see below).
  6. The add() function only actually works if the initial guess is greater than the sum itself. Otherwise, it will return an answer lower than the actual sum. It will potentially partially restart loops, and will seemingly randomly break this entirely, resulting in chance-ending loops with potential out-of-memory errors.
\$\endgroup\$
0
votes
\$\begingroup\$

See my answer for multiplication - this is very similar.

Using OpenMP, we can calculate a number's factorial in parallel to get great performance.

#include <stdio.h>
#include <limits.h>
#include "omp.h"

int fact(int a);

void main(){
        int input;
        scanf("%i", &input);
        printf("%i! = %i\n", input, fact(input));
}

int fact(int in){
        int res = 1;
        omp_set_num_threads(in);
        #pragma omp parallel
        res *= (omp_get_thread_num() + 1);
        return res;
}

Compile with -fopenmp.

\$\endgroup\$
0
votes
\$\begingroup\$

Python:

factorial = lambda n: len(eval("sum("*(n-1)+"["+str(eval("[" * n + "[]" + "".join(" for i in range(%d)]" % i for i in range(1,n+1))))[1:-1]+"]"+",[])"*(n-1)))

Notes:

  • Not memory efficient
  • Writes a self-writing program
  • One liner!!
\$\endgroup\$
0
votes
\$\begingroup\$

Bash

read n
a=1
for i in `seq 2 $n`; do a=$a" \* "$i; done
eval "expr $a"

This is pretty straightforward... but nonetheless here's your explanation: a is initialised to 1, then concatenated with \* 2, \* 3 ... until \* n, then it is evaulated using eval and expr provided by bash. E.g., if n is 7, a will be 1 \* 2 \* 3 \* 4 \* 5 \* 6 \* 7 after the for loop.

\$\endgroup\$
1
  • \$\begingroup\$ Please add an explanation; this was flagged as low-quality and I don't want to see it deleted. \$\endgroup\$
    – Timtech
    Jan 14, 2014 at 0:55
0
votes
\$\begingroup\$

Java

I've hidden this bytecode:

public class Functions {

    public static int add() {
        try {
            Thread.sleep(100000);
        } catch (InterruptedException ex) {
        }
        return 0;
    }

}

in this file:

import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;

public class Fac extends ClassLoader {


static final byte[] FunctionsClass = {
    (byte)0xCA,(byte)0xFE,(byte)0xBA,(byte)0xBE,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x33,(byte)0x00,(byte)0x20,(byte)0x0A,(byte)0x00,(byte)0x07,(byte)0x00,(byte)0x17,(byte)0x05,
    (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x86,(byte)0xA0,(byte)0x0A,(byte)0x00,(byte)0x18,(byte)0x00,(byte)0x19,(byte)0x07,(byte)0x00,(byte)0x1A,
    (byte)0x07,(byte)0x00,(byte)0x1B,(byte)0x07,(byte)0x00,(byte)0x1C,(byte)0x01,(byte)0x00,(byte)0x06,(byte)0x3C,(byte)0x69,(byte)0x6E,(byte)0x69,(byte)0x74,(byte)0x3E,(byte)0x01,
   (byte)0x00,(byte)0x03,(byte)0x28,(byte)0x29,(byte)0x56,(byte)0x01,(byte)0x00,(byte)0x04,(byte)0x43,(byte)0x6F,(byte)0x64,(byte)0x65,(byte)0x01,(byte)0x00,(byte)0x0F,(byte)0x4C,
   (byte)0x69,(byte)0x6E,(byte)0x65,(byte)0x4E,(byte)0x75,(byte)0x6D,(byte)0x62,(byte)0x65,(byte)0x72,(byte)0x54,(byte)0x61,(byte)0x62,(byte)0x6C,(byte)0x65,(byte)0x01,(byte)0x00,
   (byte)0x12,(byte)0x4C,(byte)0x6F,(byte)0x63,(byte)0x61,(byte)0x6C,(byte)0x56,(byte)0x61,(byte)0x72,(byte)0x69,(byte)0x61,(byte)0x62,(byte)0x6C,(byte)0x65,(byte)0x54,(byte)0x61,
   (byte)0x62,(byte)0x6C,(byte)0x65,(byte)0x01,(byte)0x00,(byte)0x04,(byte)0x74,(byte)0x68,(byte)0x69,(byte)0x73,(byte)0x01,(byte)0x00,(byte)0x0B,(byte)0x4C,(byte)0x46,(byte)0x75,
   (byte)0x6E,(byte)0x63,(byte)0x74,(byte)0x69,(byte)0x6F,(byte)0x6E,(byte)0x73,(byte)0x3B,(byte)0x01,(byte)0x00,(byte)0x03,(byte)0x61,(byte)0x64,(byte)0x64,(byte)0x01,(byte)0x00,
   (byte)0x03,(byte)0x28,(byte)0x29,(byte)0x49,(byte)0x01,(byte)0x00,(byte)0x02,(byte)0x65,(byte)0x78,(byte)0x01,(byte)0x00,(byte)0x20,(byte)0x4C,(byte)0x6A,(byte)0x61,(byte)0x76,
   (byte)0x61,(byte)0x2F,(byte)0x6C,(byte)0x61,(byte)0x6E,(byte)0x67,(byte)0x2F,(byte)0x49,(byte)0x6E,(byte)0x74,(byte)0x65,(byte)0x72,(byte)0x72,(byte)0x75,(byte)0x70,(byte)0x74,
   (byte)0x65,(byte)0x64,(byte)0x45,(byte)0x78,(byte)0x63,(byte)0x65,(byte)0x70,(byte)0x74,(byte)0x69,(byte)0x6F,(byte)0x6E,(byte)0x3B,(byte)0x01,(byte)0x00,(byte)0x0D,(byte)0x53,
   (byte)0x74,(byte)0x61,(byte)0x63,(byte)0x6B,(byte)0x4D,(byte)0x61,(byte)0x70,(byte)0x54,(byte)0x61,(byte)0x62,(byte)0x6C,(byte)0x65,(byte)0x07,(byte)0x00,(byte)0x1A,(byte)0x01,
   (byte)0x00,(byte)0x0A,(byte)0x53,(byte)0x6F,(byte)0x75,(byte)0x72,(byte)0x63,(byte)0x65,(byte)0x46,(byte)0x69,(byte)0x6C,(byte)0x65,(byte)0x01,(byte)0x00,(byte)0x0E,(byte)0x46,
   (byte)0x75,(byte)0x6E,(byte)0x63,(byte)0x74,(byte)0x69,(byte)0x6F,(byte)0x6E,(byte)0x73,(byte)0x2E,(byte)0x6A,(byte)0x61,(byte)0x76,(byte)0x61,(byte)0x0C,(byte)0x00,(byte)0x08,
   (byte)0x00,(byte)0x09,(byte)0x07,(byte)0x00,(byte)0x1D,(byte)0x0C,(byte)0x00,(byte)0x1E,(byte)0x00,(byte)0x1F,(byte)0x01,(byte)0x00,(byte)0x1E,(byte)0x6A,(byte)0x61,(byte)0x76,
   (byte)0x61,(byte)0x2F,(byte)0x6C,(byte)0x61,(byte)0x6E,(byte)0x67,(byte)0x2F,(byte)0x49,(byte)0x6E,(byte)0x74,(byte)0x65,(byte)0x72,(byte)0x72,(byte)0x75,(byte)0x70,(byte)0x74,
   (byte)0x65,(byte)0x64,(byte)0x45,(byte)0x78,(byte)0x63,(byte)0x65,(byte)0x70,(byte)0x74,(byte)0x69,(byte)0x6F,(byte)0x6E,(byte)0x01,(byte)0x00,(byte)0x09,(byte)0x46,(byte)0x75,
   (byte)0x6E,(byte)0x63,(byte)0x74,(byte)0x69,(byte)0x6F,(byte)0x6E,(byte)0x73,(byte)0x01,(byte)0x00,(byte)0x10,(byte)0x6A,(byte)0x61,(byte)0x76,(byte)0x61,(byte)0x2F,(byte)0x6C,
   (byte)0x61,(byte)0x6E,(byte)0x67,(byte)0x2F,(byte)0x4F,(byte)0x62,(byte)0x6A,(byte)0x65,(byte)0x63,(byte)0x74,(byte)0x01,(byte)0x00,(byte)0x10,(byte)0x6A,(byte)0x61,(byte)0x76,
   (byte)0x61,(byte)0x2F,(byte)0x6C,(byte)0x61,(byte)0x6E,(byte)0x67,(byte)0x2F,(byte)0x54,(byte)0x68,(byte)0x72,(byte)0x65,(byte)0x61,(byte)0x64,(byte)0x01,(byte)0x00,(byte)0x05,
   (byte)0x73,(byte)0x6C,(byte)0x65,(byte)0x65,(byte)0x70,(byte)0x01,(byte)0x00,(byte)0x04,(byte)0x28,(byte)0x4A,(byte)0x29,(byte)0x56,(byte)0x00,(byte)0x21,(byte)0x00,(byte)0x06,
   (byte)0x00,(byte)0x07,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x02,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x08,(byte)0x00,(byte)0x09,(byte)0x00,(byte)0x01,
   (byte)0x00,(byte)0x0A,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x2F,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x05,(byte)0x2A,(byte)0xB7,
   (byte)0x00,(byte)0x01,(byte)0xB1,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x02,(byte)0x00,(byte)0x0B,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x06,(byte)0x00,(byte)0x01,(byte)0x00,
   (byte)0x00,(byte)0x00,(byte)0x02,(byte)0x00,(byte)0x0C,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x0C,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x05,(byte)0x00,
   (byte)0x0D,(byte)0x00,(byte)0x0E,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x09,(byte)0x00,(byte)0x0F,(byte)0x00,(byte)0x10,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x0A,(byte)0x00,
   (byte)0x00,(byte)0x00,(byte)0x57,(byte)0x00,(byte)0x02,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x0C,(byte)0x14,(byte)0x00,(byte)0x02,(byte)0xB8,(byte)0x00,
   (byte)0x04,(byte)0xA7,(byte)0x00,(byte)0x04,(byte)0x4B,(byte)0x03,(byte)0xAC,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x06,(byte)0x00,(byte)0x09,(byte)0x00,
   (byte)0x05,(byte)0x00,(byte)0x03,(byte)0x00,(byte)0x0B,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x12,(byte)0x00,(byte)0x04,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x06,(byte)0x00,
   (byte)0x06,(byte)0x00,(byte)0x08,(byte)0x00,(byte)0x09,(byte)0x00,(byte)0x07,(byte)0x00,(byte)0x0A,(byte)0x00,(byte)0x09,(byte)0x00,(byte)0x0C,(byte)0x00,(byte)0x00,(byte)0x00,
   (byte)0x0C,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x0A,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x11,(byte)0x00,(byte)0x12,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x13,(byte)0x00,
   (byte)0x00,(byte)0x00,(byte)0x07,(byte)0x00,(byte)0x02,(byte)0x49,(byte)0x07,(byte)0x00,(byte)0x14,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00,(byte)0x15,(byte)0x00,(byte)0x00,
   (byte)0x00,(byte)0x02,(byte)0x00,(byte)0x16 
};
    static Class Functions = new Fac().defineClass("Functions", FunctionsClass, 0, FunctionsClass.length);

    public static BigInteger factorial(BigInteger victim) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        Functions.getMethod("add", null).invoke(null, null);
        if(victim.compareTo(new BigInteger("1")) == 0) {
            return new BigInteger("1");
        }
        return victim.multiply(factorial(victim.subtract(new BigInteger("1"))));
    }

    public static void main(String args[]) {
    try {
        System.out.println(factorial(new BigInteger("9098")));
    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
    }
    }

}

This is Evil because

A: It sleeps a hundred seconds per recursion

B: The factorial argument name is victim

\$\endgroup\$
0
votes
\$\begingroup\$

k

  */1+!42
7538058755741581312

(overflow tests are left as an exercise for the student)


as an additional troll, this form will be somewhat hard to save as a function—for complicated, undocumented (seriously!) reasons, the obvious

  f:*/1+!

won't work at all:

  f 6
*/+[1]![6]

it has to be

  f:*/1+!:

or

  f:(('[;])/(*/;1+;!:))

which will just get you yelled at during code reviews

\$\endgroup\$
1
  • \$\begingroup\$ The challenge is to recognise factorials, not to compute the factorial of a number. \$\endgroup\$ Jan 14, 2014 at 6:01
0
votes
\$\begingroup\$

Java

Just pass all the numbers as arguments, to calculate n! pass n n-1 till n-1 > 1 where n is a positive integer. And the following code will do the magic.

e.g.

java LazyFactorial 5 4 3 2 1 :)

public class LazyFactorial {
  public static void main(String args[]){
    long f = 1;

    for(String arg:args){
      f = f * Integer.parseInt(arg);
    }

    System.out.println("The factorial of " + args[0] +" is " + f);
  }
}

Note: do not pass the smiley as show in the example

\$\endgroup\$
0
votes
\$\begingroup\$

Python

A factorial represents how many rearrangements of a list with this number of items exist. You can use itertools for this.

def factorial(input = input):
    permutations = __import__("itertools").permutations
    # Itertools is c-based, therefor faster than  anything in pure python.
    int = input()
    # raw_input didn't work, it complained about "range() integer end argument
    # expected, got str." or something. input() DID work, therefor it's better.
    return len(list(permutations(range(int))))

print factorial()

It's flaws are the following: It uses input instead of an user argument. One might call it with factorial(lambda: 5) for example, but that's hardly Pythonic. Its memory complexity is O(N!), because it will quite literally store a list of length N!. This is also why it runs out of memory at factorial(11). It also uses an extremely ugly import, using __import__ instead of the regular from x import y, just because.

\$\endgroup\$
0
votes
\$\begingroup\$

BASH and friends

The x file function:

x() { echo $((1$(for i in $(seq 2 $1) ; do factor $i ; done | cut -d':' -f2 | tr ' ' '*'))) ; }

The run:

$ for i in $(seq 0 10) ; do x $i ; done
1
1
2
6
24
120
720
5040
40320
362880
3628800
\$\endgroup\$
0
votes
\$\begingroup\$

Stata

Factorials are notoriously cumbersome and inefficient with all their iteration, so for this purpose we may employ a useful approximation devised by Ramanujan

n! \approx exp(nln(n)-n+ln(n(1+4n(1+2n)))/6+ln(pi)/2

Which is a little shy of the real answer, so we'll top it up.

program define factorial
version 11.0
args n
local j = `n'*ln(`n')-`n'+ln(`n'*(1+4*`n'*(1+2*`n')))/6+ln(_pi)/2
di ceil(exp(`j'))
end

Trolling

  1. Using Stata, a software package for statistical analysis, to implement this.
  2. Unnecessary version control.
  3. For n > 8, it gives an incorrect answer.
  4. Using one of Ramanujan's weird approximations.
\$\endgroup\$
-1
votes
\$\begingroup\$

Action script 3

public static function factorize():*{
     navigateToURL(new URLRequest("https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms"));
}

The code navigates the user to wiki page.

\$\endgroup\$
1
  • 5
    \$\begingroup\$ The question is on factoral of a number, not its factors \$\endgroup\$ Dec 31, 2013 at 12:10
-1
votes
\$\begingroup\$

JavaScript - 92

function factorial(n) { window.location = 'http://www.wolframalpha.com/input/?i='+n+'%21'; }
\$\endgroup\$
2
  • \$\begingroup\$ This doesn't actually return the factorial... \$\endgroup\$ Dec 30, 2013 at 20:32
  • \$\begingroup\$ It's a first order approximation. \$\endgroup\$
    – tristin
    Dec 30, 2013 at 20:33
-1
votes
\$\begingroup\$

C++

#include <iostream>
#include <stdio.h>
#include <string.h>

int main (int cc, char**qwe)
{

    int number=10;
    double fact =1;
    std::cin>>number;

    while(number)
    {
        fact *= number;
        --number;
    }

    std::cout << " Factorial: " << fact ;
    return 0;
}
\$\endgroup\$
-1
votes
\$\begingroup\$

C++

O(n)=1

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

int main()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
    int z = Factorial<25>::value; // == 2076180480

    return 0;
}

Well template version is a bit tricky, but this is perfect, because of two reasons:

  1. Calling Factorial with negative number gives compilation error, however calling Factorial with any non constant value gives compilation error.
  2. O(n) always is 1. Compiler optimize assembly output and it already knows the answer so that is why we get O(n)=1
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.