text:
How do I find the factorial of a positive number?
The challenge:

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

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

See also The Evolution of Haskell programmer.

-1, sorry, because we're getting a huge flood of these code trolling questions and this does not really add anything new to them

Related:  http://codegolf.stackexchange.com/questions/1635/forking-factorials

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.

This is a very simple numerical computing problem that we can solve with Stirling's approximation:

As you can see, that formula features a square root, which we will also need a way to approximate. We will choose the so-called "Babylonian method" for that because it is arguably the simplest one:

Note that computing the square root this way is a good example of recursion.
Putting it all together in a Python program gives us the following solution to your problem:
def sqrt(x, n): # not the same n as below
    return .5 * (sqrt(x, n - 1) + x / sqrt(x, n - 1)) if n > 0 else x

n = float(raw_input())
print (n / 2.718) ** n * sqrt(2 * 3.141 * n, 10)

With a simple modification the above program can output a neat table of factorials:
1! =    0.92215
2! =    1.91922
3! =    5.83747
4! =   23.51371
5! =  118.06923
6! =  710.45304
7! = 4983.54173
8! = 39931.74015
9! = 359838.58817

This method should be sufficiently accurate for most applications.

+1 The simplicity and accuracy of this method makes it a clear winner

C#
Sorry, but I hate recursive function.
public string Factorial(uint n) {
    return n + "!";
}

Technically, you've satisfied the brief! ;)
+1 for brief abuse

Java
public int factorial ( int n ) {
switch(n){
case 0: return 1;
case 1: return 1;
case 2: return 2;
case 3: return 6;
case 4: return 24;
case 5: return 120;
case 6: return 720;
case 7: return 5040;
case 8: return 40320;
case 9: return 362880;
case 10: return 3628800;
case 11: return 39916800;
case 12: return 479001600;
default : throw new IllegalArgumentException();
}
}

I tried it - very efficient. Will ship with next release. :)

Beside the "magical numbers syndrom", this could actually be a good implementation as long as n<13, much less stacks.  Write it "case 4: return 432;" and you'd have a decent class, much faster than the old recursive one.

@Fabinout, the implementation is correct even for n>=13.  13!>Integer.MAX_VALUE.

Python
Of course the best way how to solve any problem is to use regular expressions:
import re

# adapted from http://stackoverflow.com/q/15175142/1333025
def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
  # Repeat while any replacements are made.
  count = -1
  while count != 0:
    # For each match, look-up corresponding value in dictionary.
    (text, count) = regex.subn(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
  return text

fdict = {
    'A': '@',
    'B': 'AA',
    'C': 'BBB',
    'D': 'CCCC',
    'E': 'DDDDD',
    'F': 'EEEEEE',
    'G': 'FFFFFFF',
    'H': 'GGGGGGGG',
    'I': 'HHHHHHHHH',
    'J': 'IIIIIIIIII',
    'K': 'JJJJJJJJJJJ',
    'L': 'KKKKKKKKKKKK',
    'M': 'LLLLLLLLLLLLL',
    'N': 'MMMMMMMMMMMMMM',
    'O': 'NNNNNNNNNNNNNNN',
    'P': 'OOOOOOOOOOOOOOOO',
    'Q': 'PPPPPPPPPPPPPPPPP',
    'R': 'QQQQQQQQQQQQQQQQQQ',
    'S': 'RRRRRRRRRRRRRRRRRRR',
    'T': 'SSSSSSSSSSSSSSSSSSSS',
    'U': 'TTTTTTTTTTTTTTTTTTTTT',
    'V': 'UUUUUUUUUUUUUUUUUUUUUU',
    'W': 'VVVVVVVVVVVVVVVVVVVVVVV',
    'X': 'WWWWWWWWWWWWWWWWWWWWWWWW',
    'Y': 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    'Z': 'YYYYYYYYYYYYYYYYYYYYYYYYYY'}

def fact(n):
    return len(multiple_replace(fdict, chr(64 + n)))

if __name__ == "__main__":
    print fact(7)

Of course indeed :)

Haskell
Short code is efficient code, so try this.
fac = length . permutations . flip take [1..]

Why it's trolling:
I'd laugh at any coder who wrote this... The inefficiency is beautiful. Also probably incomprehensible to any Haskell programmer who actually can't write a factorial function.
Edit: I posted this a while ago now, but I thought I'd clarify for future people and people who can't read Haskell.
The code here takes the list of the numbers 1 to n, creates the list of all permutations of that list, and returns the length of that list.
On my machine it takes about 20 minutes for 13!.
And then it ought to take four hours for 14! and then two and a half days for 15!.
Except that at some point in there you run out of memory.
Edit 2: Actually you probably won't run out of memory due to this being Haskell (see the comment below). You might be able to force it to evaluate the list and hold it in memory somehow, but I don't know enough about optimizing (and unoptimizing) Haskell to know exactly how to do that.

Hideous and yet so elegant, all at the same time.

Are you sure about the memory issue? At any one point, you need to hold in memory: - the list [1..n]. - One particular permutation of [1..n], consed to a thunk for the rest of the permutations (polynomial in n). - An accumulator for the length function.

Fair point, probably not actually. Didn't really think about it too much. I'll add a comment at the bottom.

C#
Since this is a math problem, it makes sense to use an application specifically designed to solve math problems to do this calculation...
Step 1:
Install MATLAB.  A trial will work, I think, but this super-complicated problem is likely important enough to merit purchasing the full version of the application.
Step 2:
Include the MATLAB COM component in your application.
Step 3:
public string Factorial(uint n) {
    MLApp.MLApp matlab = new MLApp.MLApp();
    return matlab.Execute(String.Format("factorial({0})", n);
}

Matlab for students starts at $100.  Professional versions or site licenses can go way into the thousands.

Moshe Katz - justified because factorials.

We all know from college that the most efficient way to calculate a multiplication is through the use of logarithms. After all, why else would people use logarithm tables for hundreds of years?
So from the identity a*b=e^(log(a)+log(b)) we form the following Python code:
from math import log,exp

def fac_you(x):
    return round(exp(sum(map(log,range(1,x+1)))))

for i in range(1,99):
    print i,":",fac_you(i)

It creates a list of numbers from 1 to x, (the +1 is needed because Python sucks) calculates the logarithm of each, sums the numbers, raises the e to the power of the sum and finally rounds the value to the nearest integer (because Python sucks). Python has a built-in function for calculating factorials, but it only works for integers, so it can't produce big numbers (because Python sucks). This is why the function above is needed.
Btw, a general tip for students is that if something doesn't work as expected, it's probably because the language sucks.

Wish I could give some extra votes there for the description, but Python sucks

I laughed at "fac you"

C#
Factorials are a higher level math operation that can be difficult to digest all in one go. The best solution in programming problems like this, is to break down one large task into smaller tasks.
Now, n! is defined as 1*2*...*n, so, in essence repeated multiplication, and multiplication is nothing but repeated addition. So, with that in mind, the following solves this problem:
long Factorial(int n)
{
    if(n==0)
    {
        return 1;
    }

    Stack<long> s = new Stack<long>();
    for(var i=1;i<=n;i++)
    {
        s.Push(i);
    }
    var items = new List<long>();
    var n2 = s.Pop();
    while(s.Count >0)
    {
        var n3 = s.Pop();
        items.AddRange(FactorialPart(n2,n3));
        n2 = items.Sum();
    }
    return items.Sum()/(n-1);
}

IEnumerable<long> FactorialPart(long n1, long n2)
{
    for(var i=0;i<n2;i++){
        yield return n1;
    }
}

You have a bottleneck sending all this through one CPU or core, which I think I may have solved in my answer :-)

#include <math.h>

int factorial(int n)
{
    const double g = 7;
    static const double p[] = { 0.99999999999980993, 676.5203681218851,
                                -1259.1392167224028, 771.32342877765313,
                                -176.61502916214059, 12.507343278686905,
                                -0.13857109526572012, 9.9843695780195716e-6,
                                1.5056327351493116e-7 };
    double z = n - 1 + 1;
    double x = p[0];
    int i;
    for ( i = 1; i < sizeof(p)/sizeof(p[0]); ++i )
        x += p[i] / (z + i);
    return sqrt(2 * M_PI) * pow(z + g + 0.5, z + 0.5)  * exp(-z -g -0.5) * x + 0.5;
}

Trolls:

A 100% correct way of computing factorial that completely misses the point of either doing it iteratively or recursively.
You have no idea why it works and could not generalize it to do anything else.
More costly than just computing it with integer math.
The most obvious "suboptimal" code (z = n - 1 + 1) is actually self-documenting if you know what's going on.
For extra trolling I should compute p[] using a recursive calculation of the series coefficients!

(It's the Lanczos approximation of the gamma function)

Is there any point in - 1 + 1 here? My compiler optimizes it (it's not floating point number where optimizing code like this could be dangerous), so it appears to be unneeded.

@xfix: double z = n - 1 is part of the approximation of the gamma function.  The + 1 is from the relationship that gamma(n + 1) = n! for integer n.

Ruby and WolframAlpha
This solution uses the WolframAlpha REST API to calculate the factorial, with RestClient to fetch the solution and Nokogiri to parse it. It doesn't reinvent any wheels and uses well tested and popular technologies to get the result in the most modern way possible.
require 'rest-client'
require 'nokogiri'

n = gets.chomp.to_i
response = Nokogiri::XML(RestClient.get("http://api.wolframalpha.com/v2/query?input=#{n}!&format=moutput&appid=YOUR_APP_KEY"))
puts response.xpath("//*/moutput/text()").text

Unfortunately, Javascript lacks a built-in way to compute the factorial. But, you can use its meaning in combinatorics to determine the value nevertheless:
The factorial of a number n is the number of permutations of an list of that size.
So, we can generate every list of n-digit number, check if it is a permutation, and if so, increment a counter:
window.factorial = function($nb_number) {
  $nb_trials = 1
  for($i = 0; $i < $nb_number; $i++) $nb_trials *= $nb_number
  $nb_successes = 0
  __trying__:
  for($nb_trial = 0; $nb_trial < $nb_trials; $nb_trial++){
    $a_trial_split = new Array
    $nb_tmp = $nb_trial
    for ($nb_digit = 0; $nb_digit < $nb_number; $nb_digit++){
      $a_trial_split[$nb_digit] = $nb_tmp - $nb_number * Math.floor($nb_tmp / $nb_number)
      $nb_tmp = Math.floor($nb_tmp / $nb_number)
    }
    for($i = 0; $i < $nb_number; $i++)
      for($j = 0; $j < $nb_number; $j++)
        if($i != $j)
          if($a_trial_split[$i] == $a_trial_split[$j])
            continue __trying__
    $nb_successes += 1
  }
  return $nb_successes
}

alert("input a number")
document.open()
document.write("<input type = text onblur = alert(factorial(parseInt(this.value))))>")
document.close()

Trolls:

Types hungarian notation, snake_case and unneccessary sigils. How evil is that?
Invented my own convention for jump labels, incompatible with the current use of this convention.
Every possible variable is accidentally global.
The solution is not O(n), not O(n!), but O(n^n). This alone would have sufficed to qualify here.
Incrementing a number and then converting as base-n is a bad way to generate a list of sequences. Even if we did want duplicates. Mysteriously breaking for n > 13 is not the only reason.
Of course we could have used number.toString(base), but that doesn't work for bases above 36. Yes, I know 36! is a lot, but still...
Did I mention Javascript had the modulus operator? Or Math.pow? No? Oh well.
Refusing to use ++ outside of for-loops makes it even more mysterious. Also, == is bad.
Deeply nested braceless looping constructs. Also, nested conditionals instead of AND. Also, the outer condition could have been avoided by ending the inner loop at $i.
The functions new Array, document.write (with friends) and alert (instead of a prompt or an input label) form a complete trifecta of function choice sins. Why is the input added dynamically after all?
Inline event handlers. Oh, and deep piping is hell to debug.
Unquoted attributes are fun, and the spaces around = make them even harder to read.
Did I already mention I hate semicolons?

Javascript
Javascript is a functional programming language, this means you have to use functions for everything because its faster.
function fac(n){
    var r = 1,
        a = Array.apply(null, Array(n)).map(Number.call, Number).map(function(n){r = r * (n + 1);});
    return r;
}

Can you explain?

1 is not a function. Your code is thus slow.

@ArlaudPierre r = -~(function(){}) will surely solve that.

I am on a work machine so I don't really want to install this language.  Where can I find a version that will run in my browser?

@joeytwiddle Do you have google chrome? If so, just run it on the console (I get there by: F12 (key for "inspect element")->Console). Other browsers probably have this too. http://ideone.com/ has Javascript. http://jsfiddle.net/ runs Javascript too.

I'm a bit scared of using Google because my boss has an account with them, and I don't want him to know I'm playing golf at work. I was looking for an extension for Firefox that could run Javascript, but I can't seem to find one. Some of my friends run Javascript on jsfiddle.net but that's using somebody else's electricity which is a bit like stealing. My mum said I shouldn't hang around with people like that, but they are my friends so what can I do? Anyway she sometimes takes more creamer than she needs. Thanks for the tips, I use Ctrl-Shift-J or K in Firefox. Disclaimer: #comment-trolling

@Luka "Javascript is a functional programming language, this means you have to use functions for everything because its faster." made me laugh so hard.  Best answer so far.

Using Bogo-Sort in Java
public class Factorial {
    public static void main(String[] args) {
        //take the factorial of the integers from 0 to 7:
        for(int i = 0; i < 8; i++) {
            System.out.println(i + ": " + accurate_factorial(i));
        }
    }

    //takes the average over many tries
    public static long accurate_factorial(int n) {
        double sum = 0;
        for(int i = 0; i < 10000; i++) {
            sum += factorial(n);
        }
        return Math.round(sum / 10000);
    }

    public static long factorial(int n) {
        //n! = number of ways to sort n
        //bogo-sort has O(n!) time, a good approximation for n!
        //for best results, average over several passes

        //create the list {1, 2, ..., n}
        int[] list = new int[n];
        for(int i = 0; i < n; i++)
            list[i] = i;

        //mess up list once before we begin
        randomize(list);

        long guesses = 1;

        while(!isSorted(list)) {
            randomize(list);
            guesses++;
        }

        return guesses;
    }

    public static void randomize(int[] list) {
        for(int i = 0; i < list.length; i++) {
            int j = (int) (Math.random() * list.length);

            //super-efficient way of swapping 2 elements without temp variables
            if(i != j) {
                list[i] ^= list[j];
                list[j] ^= list[i];
                list[i] ^= list[j];
            }
        }
    }

    public static boolean isSorted(int[] list) {
        for(int i = 1; i < list.length; i++) {
            if(list[i - 1] > list[i])
                return false;
        }
        return true;
    }
}

This actually works, just very slowly, and it isn't accurate for higher numbers.

Python
Just an O(n!*n^2) algorithm to find the factorial. Base case handled. No overflows.
def divide(n,i):
    res=0
    while n>=i:
         res+=1
         n=n-i
    return res

def isdivisible(n,numbers):
    for i in numbers:
         if n%i!=0:
             return 0
         n=divide(n,i)
    return 1

def factorial(n):
    res = 1
    if n==0: return 1 #Handling the base case
    while not isdivisible(res,range(1,n+1)):
         res+=1
    return res

PERL
Factorial can be a hard problem.  A map/reduce like technique -- just like Google uses -- can split up the math by forking off a bunch of processes and collecting the results.  This will make good use of all those cores or cpus in your system on a cold winter's night.
Save as f.perl and chmod 755 to make sure you can run it.  You do have the Pathologically Eclectic Rubbish Lister installed, don't you?
#!/usr/bin/perl -w
use strict;
use bigint;
die "usage: f.perl N (outputs N!)" unless ($ARGV[0] > 1);
print STDOUT &main::rangeProduct(1,$ARGV[0])."\n";
sub main::rangeProduct {
    my($l, $h) = @_;
    return $l    if ($l==$h);
    return $l*$h if ($l==($h-1));
    # arghhh - multiplying more than 2 numbers at a time is too much work
    # find the midpoint and split the work up :-)
    my $m = int(($h+$l)/2);
    my $pid = open(my $KID, "-|");
      if ($pid){ # parent
        my $X = &main::rangeProduct($l,$m);
        my $Y = <$KID>;
        chomp($Y);
        close($KID);
        die "kid failed" unless defined $Y;
        return $X*$Y;
      } else {
        # kid
        print STDOUT &main::rangeProduct($m+1,$h)."\n";
        exit(0);
    }
}

Trolls:

forks O(log2(N)) processes
doesn't check how many CPUs or cores you have
Hides lots of bigint/text conversions that occur in every process
A for loop is often faster than this code

TIL that in perl ARGV[0] is actually the first argument and not the script!

@plg I believe $0 might contain the script filename, but that is not the same as $ARGV[0]

Yep, that's what I read. I just found it surprising that in perl it's not $ARGV[0] because most languages I know a bit have it there

Ruby
f=->(n) { return 1 if n.zero?; t=0; t+=1 until t/n == f[n-1]; t }

The slowest one-liner I can imagine. It takes 2 minutes on an i7 processor to calculate 6!.

Mathematica
factorial[n_] := Length[Permutations[Table[k, {k, 1, n}]]]

It doesn't seem work for numbers larger than 11, and factorial[11] froze up my computer.

Well, there is an easy solution in Golfscript. You could use a Golfscript interpreter and run this code:
.!+,1\{)}%{*}/

Easy huh :) Good luck!

I don't know GolfScript, but this one disappoints me... Based on the other GolfScript examples on this site, I would have expected the answer to be !

That is the negation operator. 0 becomes 1 and everything else becomes 0.

The correct approach for these difficult math problems is a DSL. So I'll model this in terms of a simple language
data DSL b a = Var x (b -> a)
             | Mult DSL DSL (b -> a)
             | Plus DSL DSL (b -> a)
             | Const Integer (b -> a)

To write our DSL nicely, it's helpful to view it as a free monad generated by the algebraic functor
F X = X + F (DSL b (F X)) -- Informally define + to be the disjoint sum of two sets

We could write this in Haskell as
Free b a = Pure a
         | Free (DSL b (Free b a))

I will leave it to the reader to derive the trivial implementation of
join   :: Free b (Free b a) -> Free b a
return :: a -> Free b a
liftF  :: DSL b a -> Free b a

Now we can descibe an operation to model a factorial in this DSL
factorial :: Integer -> Free Integer Integer
factorial 0 = liftF $ Const 1 id
factorial n = do
  fact' <- factorial (n - 1)
  liftF $ Mult fact' n id

Now that we've modeled this, we just need to provide an actual interpretation function for our free monad.
denote :: Free Integer Integer -> Integer
denote (Pure a) = a
denote (Free (Const 0 rest)) = denote $ rest 0
...

And I'll leave the rest of the denotation to the reader.
To improve readability, it's sometimes helpful to present a concrete AST of the form
data AST = ConstE Integer
         | PlusE AST AST
         | MultE AST AST

and then right a trivial reflection
reify :: Free b Integer -> AST

and then it's straightforward to recursively evaluate the AST.

Python
Below is a Python version of the solution, which is not limited to the 32 bit (or 64 bit on a very recent system) limit for integer numbers in Python. To get around this limitation, we shall use a string as input and output for the factorial routine and internally split the string in it's digits to be able to perform the multiplication.
So here is the code: the getDigits function splits a string representing a number in to its digits, so "1234" becomes [ 4, 3, 2, 1 ] (the reverse order just makes the increase and multiply functions simpler). The increase function takes such a list and increases it by one. As the name suggests, the multiply function multiplies, e.g. multiply([2, 1], [3]) returns [ 6, 3 ] because 12 times 3 is 36. This works in the same way as you would multiply something with pen and paper.
Then finally, the factorial function uses these helper functions to calculate the actual factorial, for example factorial("9") gives "362880" as its output.
import copy

def getDigits(n):
    digits = []
    for c in n:
        digits.append(ord(c) - ord('0'))

    digits.reverse()
    return digits

def increase(d):
    d[0] += 1
    i = 0
    while d[i] >= 10:
        if i == len(d)-1:
            d.append(0)

        d[i] -= 10
        d[i+1] += 1
        i += 1

def multiply(a, b):
    subs = [ ]
    s0 = [ ]
    for bi in b:

        s = copy.copy(s0)
        carry = 0
        for ai in a:
            m = ai * bi + carry
            s.append(m%10)
            carry = m//10

        if carry != 0:
            s.append(carry)

        subs.append(s)
        s0.append(0)

    done = False
    res = [ ]
    termsum = 0
    pos = 0
    while not done:
        found = False
        for s in subs:
            if pos < len(s):
                found = True
                termsum += s[pos]

        if not found:
            if termsum != 0:
                res.append(termsum%10)
                termsum = termsum//10
            done = True
        else:
            res.append(termsum%10)
            termsum = termsum//10
            pos += 1

    while termsum != 0:
        res.append(termsum%10)
        termsum = termsum//10

    return res

def factorial(x):
    if x.strip() == "0" or x.strip() == "1":
        return "1"

    factorial = [ 1 ]
    done = False
    number = [ 1 ]
    stopNumber = getDigits(x)
    while not done:
        if number == stopNumber:
            done = True

        factorial = multiply(factorial, number)
        increase(number)

    factorial.reverse()

    result = ""
    for c in factorial:
        result += chr(c + ord('0'))

    return result

print factorial("9")

Notes
In python an integer doesn't have a limit, so if you'd like to do this manually you can just do
fac = 1
for i in range(2,n+1):
    fac *= i

There's also the very convenient math.factorial(n) function.
This solution is obviously far more complex than it needs to be, but it does work and in fact it illustrates how you can calculate the factorial in case you are limited by 32 or 64 bits. So while nobody will believe this is the solution you've come up with for this simple (at least in Python) problem, you can actually learn something.

There is no limit on integer numbers in Python... right? You might need to explain this better.

@Riking Yes, in python there's no limit for integers. I've added a few notes to make it more clear.

Just go to Google and type in your factorial:
5!

http://lmgtfy.com/?q=5!

Python
The most reasonable solution is clearly to check through all numbers until you find the one which is the factorial of the given number.
print('Enter the number')
n=int(input())
x=1
while True:
    x+=1
    tempx=int(str(x))
    d=True
    for i in range(1, n+1):
        if tempx/i!=round(tempx/i):
            d=False
        else:
            tempx/=i
    if d:
        print(x)
        break

A most elegant recursive solution in C
Every one knows the most elegant solutions to factorials are recursive.
Factorial:
0! = 1
1! = 1
n! = n * (n - 1)!

But multiplication can also be defined recursively as successive additions.
Multiplication:
n * 0 = 0
n * 1 = n
n * m = n + n * (m - 1)

And so can addition as successive incrementations.
Addition:
n + 0 = n
n + 1 = (n + 1)
n + m = (n + 1) + (m - 1)

In C, we can use ++x and --x to handle the primitives (x + 1) and (x - 1) respectively, so we have everything defined.
#include <stdlib.h>
#include <stdio.h>

// For more elegance, use T for the type
typedef unsigned long T;

// For even more elegance, functions are small enough to fit on one line

// Addition
T A(T n, T m) { return (m > 0)? A(++n, --m) : n; }

// Multiplication
T M(T n, T m) { return (m > 1)? A(n, M(n, --m)): (m? n: 0); }

// Factorial
T F(T n) { T m = n; return (m > 1)? M(n, F(--m)): 1; }

int main(int argc, char **argv)
{
    if (argc != 2)
        return 1;

    printf("%lu\n", F(atol(argv[1])));

    return 0;
}

Let's try it out:
$ ./factorial 0
1
$ ./factorial 1
1
$ ./factorial 2
2
$ ./factorial 3
6
$ ./factorial 4
24
$ ./factorial 5
120
$ ./factorial 6
720
$ ./factorial 7
5040
$ ./factorial 8
40320

Perfect, although 8! took a long time for some reason. Oh well, the most elegant solutions aren't always the fastest. Let's continue:
$ ./factorial 9

Hmm, I'll let you know when it gets back...

Python
As @Matt_Sieker's answer indicated, factorials can be broken up into addition- why, breaking up tasks is the essence of programming. But, we can break that down into addition by 1!
def complicatedfactorial(n):
    def addby1(num):
        return num + 1
    def addnumbers(a,b):
        copy = b
        cp2 = a
        while b != 0:
            cp2 = addby1(cp2)
            b -= 1
    def multiply(a,b):
        copy = b
        cp2 = a
        while b != 0:
            cp2 = addnumbers(cp2,cp2)
    if n == 0:
        return 1
    else:
        return multiply(complicatedfactorial(n-1),n)

I think this code guarantees an SO Error, because

Recursion- warms it up

Each layer generates calls to multiply

which generates calls to addnumbers

which generates calls to addby1!

Too much functions,right?

Javascript
Obviously the job of a programmer is to do as little work as possible, and to use as many libraries as possible. Therefore, we want to import jQuery and math.js. Now, the task is simple as this:
$.alert=function(message){
    alert(message);
}$.factorial=function(number){
    alert(math.eval(number+"!"));
    return math.eval(number+"!");
}
$.factorial(10);

Python
With just a slight modification of the standard recursive factorial implementation, it becomes intolerably slow for n > 10.
def factorial(n):
    if n in (0, 1):
        return 1
    else:
        result = 0
        for i in range(n):
            result += factorial(n - 1)
        return result

bash
Factorials are easily determined with well known command line tools from bash.
read -p "Enter number: " $n
seq 1 $n | xargs echo | tr ' ' '*' | bc

As @Aaron Davies mentioned in the comments, this looks much tidier and we all want a nice and tidy program, don't we?
read -p "Enter number: " $n
seq 1 $n | paste -sd\* | bc

i recommend the highly-underrated paste command: seq 1 $n | paste -sd\* | bc

@AaronDavies paste does look like a regular English word and with that easy to remember. Do we really want that? ;o)

TI-Basic 84
:yumtcInputdrtb@gmail And:cReturnbunchojunk@Yahoo A!op:sEnd:theemailaddressIS Crazy ANSWER LOL

It really works :)

Bash
#! /bin/bash

function fact {
    if [[ ${1} -le 1 ]]; then
        return 1
    fi;

    fact $((${1} - 1))
    START=$(date +%s)
    for i in $(seq 1 $?); do sleep ${1}; done
    END=$(date +%s)
    RESULT=$(($END - $START))
    return $RESULT
}

fact ${1}
echo $?

Let's try to do it by the Monte Carlo Method. We all know that the probability of two random n-permutations being equal is exactly 1/n!. Therefore we can just check how many tests are needed (let's call this number b) until we get c hits. Then, n! ~ b/c.
Sage, should work in Python, too
def RandomPermutation(n) :
    t = range(0,n)
    for i in xrange(n-1,0,-1):
        x = t[i]
        r = randint(0,i)
        t[i] = t[r]
        t[r] = x
    return t

def MonteCarloFactorial(n,c) :
    a = 0
    b = 0
    t = RandomPermutation(n)
    while a < c :
        t2 = list(t)
        t = RandomPermutation(n)
        if t == t2 :
            a += 1
        b += 1
    return round(b/c)

MonteCarloFactorial(5,1000)
# returns an estimate of 5!

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

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.

Ok, now it works.   http://ideone.com/NV4xyv

The trolliness derives from generating all NN 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.

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

    }

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'

I think you mess up together the "gamma distribution and the "gamma function" ;)

C#
using System.Numerics;
public static BigInteger GetFactorialRecursive(uint n)
{
  if (n == 0)
  {
     return 1;
  }
  return GetFactorialRecursive(n-1)*n;
}

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\{)}%{*}/

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.

dc
echo 10 | dc -e "?[d1-d1<F*]dsFxp"

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.

C
Sweet and simple.
#include <math.h>
#define factorial(n) tgamma((n)+1)

But I see now that it is equivalent to an R answer given earlier.

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

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

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

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

Mathematica, 21 characters

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

f[5]

120

How this works: clue

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)

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.

Please add an explanation; this was flagged as low-quality and I don't want to see it deleted.

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:

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).
Lots (and lots (and lots)) of recursion without the use of for loops.
Almost instant correct answer for 0 (I know it isn't positive, but it's easy) and 1, but gets extremely sluggish quickly.
Prepare for CPU suicide. (It is at least light on RAM...if that counts for anything...)
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).
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.

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

The challenge is to recognise factorials, not to compute the factorial of a number.

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.

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

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

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

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.

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

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

Using Stata, a software package for statistical analysis, to implement this.
Unnecessary version control.
For n > 8, it gives an incorrect answer.
Using one of Ramanujan's weird approximations.

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

JavaScript - 92
function factorial(n) { window.location = 'http://www.wolframalpha.com/input/?i='+n+'%21'; }

This doesn't actually return the factorial...

It's a first order approximation.

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:

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

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.

The question is on factoral of a number, not its factors

Javascript
The solution is very easily done using a while loop
function f(n){ var e = n; while (n--){ if (n < 1) break; e*=n;} return e}

Welcome to PP&CG, @BenJohnsonmk2.  You should read up on what [tag:code-trolling] questions require of their answers. An answer should "give code that works, but is useless, severely frustrating the OP."  Your answer needs work!  You can edit your answer at any time to make it "better".  Cheers.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
how to find n'th number in the decimal expansion of a proper fraction?
Given three integers N,D,R write a program to output Rth digit after the decimal point in the decimal expansion for a given proper fraction N/D.

Is it ok to write a function or do we have to provide a complete program? Also with Rth digit - do you want to have the Rth digit after the decimal point or the Rth digit in total?

Mat I suggest you include some test cases?

This question seems underspecified. Since it is codegolf the shortest answer wins, however edge case behavior and precision requirements are not given. Need all answers report '0' for rational numbers (for example the 5th digit of 1/2)? What about fractions that would result in a number less than FLOAT_MIN in whatever language the answer is composed in? The assumption I make is that arbitrary precision and trailing zeros are required, but it would be nice if this were stated/refuted in the question.

GolfScript 17
10\?@abs*\abs/10%

GolfScript can't handle real numbers well, but multiplying by powers of 10 is equivalent.
Here's an explanation and walkthrough with sample input, for any of you who are new to GolfScript, since I think this is a nice simple introduction:
59 -17 5
10\ #Place 10 on the stack and then switch the top 2 elements
-> 59 -17 10 5
? #Exponentiate
-> 59 -17 100000
@ #Rotate top 3 elements
-> -17 100000 59
abs #Take absolute value of top element
-> -17 100000 59
* #Multiply the top 2 elements
-> -17 5900000
\ #Switch top 2 elements
-> 5900000 -17
abs #Take absolute value of top element
-> 5900000 17
/ #Do integer division
-> 347058
10% #Place 10 on the stack and then take modulo
-> 8

Doesn't work with negative N or D, e.g. -1 3 1.

@Howard shoot good call.  I've added 2 calls to abs.  This edge case is now responsible for almost a third of the characters!  Anybody got a shorter alternative?

How does it handle 1 70000 3?  1 2 5?

@DavidCarraher For 1 70000 3 it calculates 10^3/70000 using integer division, which is 0, as desired.  Note that 1 70000 5 = 10^5/70000 = 1, as desired.  Similarly, 1 2 5=10^5/2=0, since the decimal expansion of 1/2 has a 0 in the fifth decimal place.

Java
static int digit(int N, int D, int R) {
    if (D < 0) D = -D;
    if (N < 0) N = -N;
    int Q=0;
    while (R-- > 0) {
        while (N >=D) N -=D;
        int P=N = ((N+N)<<1)+N;
        for (Q=P^P; N >D; N -=D) Q++;
        while (P >=D) P -=D;
        N = P<<1;
    }
    for (; N >= 0; N -=D) R++;
    return (Q<<1) + R;
}

This code

avoids multiplication and division
splits decimal digit in 5- and 2-digit (Q and final R) internally

Explanation
When dividing manually you get digits by multiplying remainders by 10 and comparing the results to multiples of the divisor
10 / 17 = Digit 0, Remainder 10 (x 10)
100 / 17 = Digit 5, Remainder 15 (x 10)
 150 / 17 = Digit 8, Remainder 14 (x 10)
  140 / 17 = Digit 8, Remainder 4 (x 10)
etc.

So the basic code (ignoring all digits except the R-th) would be
static int digitA(int N, int D, int R) {
    while (R-- > 0) {
        N = N % D;
        N = N * 10;
    }
    return N / D;
}

Replacing multiplications and divisions by adding/subtracting and shifting results in
while (R-- > 0) {
    while (N >= D) N = N - D;
    N = ((N << 2) + N) << 1;
}
int digit = 0;
while (N > D) { digit++; N = N - D; }
return digit;

As R is -1 after the first loop, it can be used to replace digit afterwards.
With avoiding shifting by more than 1 and introducing intermediate P the code becomes
while (R-- > 0) {
    while (N >= D) N = N - D;
    int P = ((N + N) << 1) + N;
    N = P << 1;
}
for ( ; N >= D; N = N - D) R++;
return R;

The number of loop runs can be reduced by "splitting the decimal digit into two digits with base 5 and 2".
The above manual division schema would become something like
10 / 17 = 2-Digit 0, Remainder 10 (x 5)
50 / 17 = 5-Digit 2, Remainder 16 (x 2)
32 / 17 = 2-Digit 1, Remainder 15 (x 5) --> 10-digit = 2*2 + 1
75 / 17 = 5-Digit 4, Remainder 7 (x 2)
14 / 17 = 2-Digit 0, Remainder 14 (x 5) --> 10-digit = 4*2 + 0
70 / 17 = 5-Digit 4, Remainder 2 (x 2)
4 / 17 = 2-Digit 0, Remainder 4 (x 5) --> 10-digit = 4*2 + 0
etc.

As only the R-th decimal digit is to be returned, only the R-th 5-digit before the R-th 2-digit is required to compose the R-th decimal digit.
int P=N = ((N+N)<<1)+N; // N = N * 5
for (Q=P^P; N >D; N -=D) Q++; // Q=digit(5)
//...
return (Q<<1) + R;

The rest is some "obfuscation"

P^P is zero - inspired by machine code where XORing may be the most efficient way to set a register to zero :-)
The line while (P >=D) P -=D; is the same as P=N; - but is more "smiling" :-)

Mind sharing an explanantion as well?

@CinCout Added explanation, admitting it was hard to recall what I was thinking/intending so long ago ... :-)

Mathematica: 36 chars
f = RealDigits[#1/#2, 10, 1, -#3][[1, 1]] &

Test case:
f[1, 70000, 5]

1

Python: 96 bytes
The following code counts the number of digits after the decimal point, e.g. for N = 3 and D = 17, fracnum(N,D,7) = 5 since N/D = 0.176470588235.
def fracnum(N,D,R):
    v, d = abs(N)*10, abs(D)
    while R:
        (v, r, R) = (v*10, v, R-1) if v < d else ((v%d)*10, v//d, R-1)

    return r

This function can be written more compact as:
def f(N,D,R):
 v,d=abs(N)*10,abs(D)
 while R:v,r=(((v%d)*10,v//d),(v*10,v))[v<d];R-=1
 return r

You didn't give yourself a score, but if you golf your code like this (replacing \n with literal newlines): def g(n,d,r):\n f=abs;v,d=f(n)*10,f(d);\n while r:(v,e,r)=(((v%d)*10,v//d,r-1),(v*10,v,r-1))[v<d]\n return e it should come out to 105 bytes.

Ah ok, I see. I'll make an edit showing a more compact version. Thanks!

+1, oops I missed the r-1 nice answer

Awk: 38
BEGIN{b=n/d"";print substr(b,r+2,1)}

Called by the slightly cumbersome awk -f division.awk -v n=? -v d=? -v r=? where ? represents the variable you want in there. Note that this is limited by precision, so choice of 1 4 3 would result in a blank line.

Python: 69 bytes
def f(N,D,R):
    return ('%.{0}f'.format(R+1)%(float(N)/float(D)))[-2]

(first time posting here, please be gentle for any formatting/misc errors :D)

BASH - 52
f=$(echo "scale=$R; $N/$D"|bc -l)
n=${f:$((${#f}-1))}

JavaScript - 40
function f(n,d,r){return(n/d%1+'')[r+1]}

PHP — 54 (Exact precision)
echo bcdiv(bcmul(bcpow(10,$r+1),abs($n)),abs($d))[$r];

PHP — 41 (Not so exact precision (eventual floating point errors))
echo strval(abs(pow(10,$r+1)*$n/$d))[$r];

Mathematica 63 65
This now handles rational numbers close to zero.
Should work to (one million places - no. places to the left of decimal point).
f[n_,d_,r_]:=({w,z}=RealDigits[N[n/d,10^6]];If[z+r<1,0,w[[z+r]]])

Testing
The following returns the digits at positions min through max, allowing for easy checking of results.
g[n_, d_, {min_, max_}] := Grid@{{"num", "den", "decimal", "digits " <> ToString@min <>
" to " <> ToString@max}, {n, d, N[n/d, max], Table[f[n, d, k], {k, min, max}]}}

Verify the digits of 1/7 from 3 to 7 places to the right of the decimal point.
g[1, 7, {3, 7}]

g[1, 7000, {3, 6}]

g[1, 2, {1, 5}]

David, I also used RealDigits ;-)

@Yves Yes, and you exploited the third and fourth arguments in ways I was until now unaware of!  Nice.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How do I convert a word document to a pdf?
Help guys my assignment says it needs to be in .pdf format but I did it in Word. I'm really stuck.
How do I take a word document in .docx format and make a .pdf that contains all the text from it? Bonus points if it also contains all the images and any formatting, but text is a bare minimum. The sample file I'll be using will be this one, though your solution should be generic.
I don't want it to go through any unnecessary processing steps - simply encoding then decoding the document in base64 or whatever is not in the spirit of the question, though creative use of cowsay will be an exception to this. Standard rules of code trolling apply - the solution should be technically correct, all steps should be technically necessary, the result should be technically useless. This should be more of a "Rube Goldberg" style program, than an obfuscation and obtuseness competition.
Most upvotes on answers other than my own by 5/1/14 wins.
Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here.

This assignment is way complex, but I'm certain that the only proper approach would be to use a Preview Handler in a WPF application, take a screenshot of that, save the bitmap as a GIF and then print that as a PDF

Code-trolling is in the process of being removed, as per the official stance. This post has a fair amount of votes on the question and the answers, and even though it recieved over 50% "delete" votes on the poll, it is one of the more well specified [code-trolling] posts. Therefore, I am locking it for historical significance.

Ok this is a little tricky but not too bad because pdf uses the same graphics model as postscript which means that once you have postscript it is quite trivial to convert it to pdf and postscript is way to drive printers all you have to do is print to get postscript.
Now you could write a program to convert postscript to pdf, but we don't have to there is ghostscript, which was written for unix and works just fine on linux (no major differences for this project). Unfortunately word only runs on windows, so you need two computers, and to convince windows that the linux computer is a printer you need a serial cable and a null modem. If your computer(s) don't have serial ports usb to rs232 converters work just fine (I recommend ones with a fttdi chipset). Now hook up the two computers with the serial cable and the null modem and verify that you can communicate (make sure that your parameters match).
Ok now that you have them talking it is time to convince your windows box that the linux box is a printer: just install the printer driver for the applewriter II and say it is connected to the serial port. Now when you print you send postscript to the linux box. the next step is to save it as a file.
Now scoot over to your linux box and use this simple command:
dd -if=/dev/ttyS0 -of=- -bs=1 | ps2pdf - - | sed -e '' >tmpfile && mv tmpfile file.pdf

and as simple as that you are done.

This can actually be made to work (if you send a signal to dd when you are finished) but there are easier ways like printing to a file and running gostscript on your windows box, and although fttdi makes good quality usb to serial converters it is a royal pain to install the drivers.

Though testing this is beyond my means, a bit of background reading suggests that this is both valid and awful. Good work!

I thought about including instructions for making a null modem, just so a soldering iron was needed.

These days many printers are combination printer/scanner with automatic document feeders.  It will be simple.

Print the document.
Scan the print out.

This is how people actually do it... I wish I were kidding. And, this is [tag:code-trolling], where is your code?

PHP
This code produces PDF files that should print out perfectly on your ticker tape machine. If you want to view the PDF files on your monitor, you might have to zoom in a bit.
Example source document

PDF output (viewed in browser)

Source code
<?php

header("Content-Type: application/pdf");

$s = docx2txt("word-file.docx"); // <-- Insert filename here!
echo txt2pdf($s);

function docx2txt($filename) {
  if (!($z=zip_open($filename))) return false; // Can't open file
  while ($r=zip_read($z)) {
    if (zip_entry_name($r)!="word/document.xml") continue;
    if (!zip_entry_open($z,$r)) return false; // Can't open XML data
    for ($s="";;) {
      $c=zip_entry_read($r);
      if ($c===false || $c=="") break;
      $s.=$c;
    }
    return trim(preg_replace('/\s+/',' ',preg_replace('/<[^>]*>/','',$s)));
  }
  return false; // Can't find XML data
}

function txt2pdf($text) {
  $width="".ceil(strlen($text)*7.2);
  $text=str_replace('(','\050',str_replace(')','\051',$text));
  $length=strlen($text);
  $wlen=strlen($width);
  $len4="".(44+$length);
  $xr3=sprintf("%010d",174+$wlen);
  $xr4=sprintf("%010d",449+$wlen);
  $xrstart=544+$wlen+strlen($len4)+$length;
  return "%PDF-1.1\n%¥±ë\n\n1 0 obj\n  << /Type /Catalog\n     /Pages 2 0 R\n" .
         "  >>\nendobj\n\n2 0 obj\n  << /Type /Pages\n     /Kids [3 0 R]\n   " .
         "  /Count 1\n     /MediaBox [0 0 $width 14]\n  >>\nendobj\n\n3 0 obj" .
         "\n  <<  /Type /Page\n      /Parent 2 0 R\n      /Resources\n       " .
         "<< /Font\n           << /F1\n               << /Type /Font\n       " .
         "           /Subtype /Type1\n                  /BaseFont /Courier\n " .
         "              >>\n           >>\n       >>\n      /Contents 4 0 R\n" .
         "  >>\nendobj\n\n4 0 obj\n  << /Length $len4 >>\nstream\n  BT\n    /" .
         "F1 12 Tf\n    0 3 Td\n    ($text) Tj\n  ET\nendstream\nendobj\n\nxr" .
         "ef\n0 5\n0000000000 65535 f \n0000000018 00000 n \n0000000077 00000" .
         " n \n$xr3 00000 n \n$xr4 00000 n \ntrailer\n  <<  /Root 1 0 R\n    " .
         "  /Size 5\n  >>\nstartxref\n$xrstart\n%%EOF";
}

?>

Note: The txt2pdf() function is based on a minimal PDF file made by Brendan Zagaeski.

Where's the troll?

On UNIX systems:
mv document.docx document.pdf && cowsay "code-trolling is cool"

On Windows:
ren document.docx document.pdf

note: won't work of course... Just found it funny

I believe this shell script to be a simple and intuitive method of solving the problem. Is there a better way?
( echo $'<svg>\n<text y="10">';
  unzip -p ./YOUR_FILENAME_HERE.docx word/document.xml |
  sed -e 's/<[^>]\{1,\}>//g; s/[^[:print:]]\{1,\}//g';
  echo $'\n</text>\n</svg>' ) |
inkscape -f /dev/fd/0 -D -A ./OUTPUT_FILENAME_HERE.pdf

" why does this swap to floppy? " ;)

This link will surely gonna help you. http://javahive.in/convert-word-doc-to-pdf-file-in-java/ you just have to run this java code and your pdf will be there for you.

Would have been funnier if it was just the link.

Windows Batch
The easiest way to convert a file: change the extension!
:: convert.cmd

xcopy "%~dpnx0" "%~dpn0.pdf"

Spoiler/troll: (hover below to see)

 Oops...did I forget that you could convert even a file with a .exe extension? So much for that... ;)
 Also, I'm too lazy to code the guards.
 And I thought I'd add a little extra troll in this: it doesn't even touch the data inside... (doesn't parse it to make it a valid PDF)


text:
An unintentional-looking but crash-causing bug
There are a range of questions revolving around this concept, but these all seem to just involve causing a crash, resulting in many answers which are very obviously designed to cause a crash. So the challenge I set you is to write some plausible code (although what the codes supposed "intention" is I leave up to you), that crashes either the entire target OS, or just itself, in a way which is not immediately obvious. (I realize that what counts as "immediately obvious" is subjective, but hopefully the challenge is still reasonably clear).
The winner is the answer with the most votes after 5 days.

Removed tag code-challenge since there is no objective criterion given.

There have been too many occurrences of these in my actual code. I can't remember any of them, though.

Related: the Underhanded C Contest has a bunch of problems with a similar goal, and some quite clever solutions to them.

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

C, linux. Crashes system if run as root
/* Fork child process, wait 5 seconds and kill it */
pid_t pid = fork();
if(pid =! 0) {
    /* Parent */
    sleep(5);
    kill(pid, 11);
}
else {
    /* Child process. Would contain some code */
}

By changing != to =!, an innocent comparison is turned into an assignment. And given that pid 1 is init, and killing init causes a kernel panic, this is not code you would want to run as root :)

init ignores SIGKILL, to kernal panic you must send it SIGSEGV, signal 11

Ah, rats. Edited to change, but that makes it a lot less inconspicuous. Would SIGTERM work too?

No: http://unix.stackexchange.com/questions/7441/can-root-kill-init-process

I would hide SIGSEGV by using numeric code. After all, it could've been a mistake.

I like that idea, edited :)

I have been away and haven't looked at this question for a few days, sorry for accepting it late.

C#
Let's just initialize a list of bytes with every byte value from 0 to 255.
List<byte> bytes = new List<byte>();
for (byte i = 0; i <= 255; i++)
{
    bytes.Add(i);
}

Out of memory? I distinctly recall having more than 256 bytes installed...
Spoiler:

 A byte will always be less than or equal to 255. Addition wraps around from 255 to 0.

This took me longer than it should've to figure out

Doesn't the C# compiler warn you that you're pbzcnevat jvgu n pbafgnag gung'f bhg bs obhaqf? (rot13'd to not spoil the riddle)

@Dennis probably not, because lbh pna pbzcner qvssrerag ahzrevp glcrf jvgubhg reebe/jneavat, naq gur pbafgnag va dhrfgvba vf n inyvq vag.

@DennisKaarsemaker It does warn you if lbh hfr 'yrff-guna gjb svsgl fvk' which is why I didn't do that. There are no warnings here though.

ah, yes, that makes sense.

I'm still having trouble working out why this works, so I think it fulfills its purpose well!

Here's a decode/encoder str.toLowerCase().split('').map(function(c) { return c < 'a' || c > 'z' ? c : String.fromCharCode(((c.charCodeAt(0) - 'a'.charCodeAt(0) + 13) % 26) + 'a'.charCodeAt(0)); }).join('')

@handuel, I had problems too ;__; The point is, that jura v=255 gura arkg ybbc vgrengvba znxrf v=0 (orpnhfr bs olgr glcr). Guhf ybbc arire raqf (nyjnlf v<=255) naq nqqf vasvavgr pbhag bs olgrf gb gur yvfg (rot13.com)

Here's another encoder/decoder: vi ig??:qa

C
#include <stdio.h>

int main(void) {
   fputs(stdout, "Hello, world!\n");
   return 0;
}

(Compiler warnings will give it away.)

JavaScript
var arr = [3,6,1,54,2,-4,8,10,3,7]
function qs(a) {
    if (a.length < 2) return a
    var part = a.shift()
    var higher = [], lower = []
    for (var i = 0; i < a.length; i ++) {
        var x = a[i] // *** THIS LINE ***
        (x < part ? lower : higher).push(x)
 }
    return qs(lower).concat([part]).concat(qs(higher))
}
alert(qs(arr))

Working quicksort, except for the fact that lack of semicolon on the line I marked with a comment causes it to parse wrong and crash.
Adding a semicolon at the end of that line fixes it.

GTB
:""→_[_+"+"→_]

Crashes the calculator because [_+ should be ["_"+, but since it isn't, the calculator runs out of memory, potentially clearing the RAM in the wrong way.

["_"+ looks like a face that's a little upset with me

C++
Inputs names and store them in a vector.  Prints names upon entry of flag value.  Asks if user thought of more names; if so, inputs names.
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void print(const vector<string>& v) {

  for (int i = 0; i <= names.size(); i++)
    cout << v[i] << endl;
}

void input(vector<string>& v) {

  string tmp;

  cout << "Enter a list of names seperated by returns: ";

  do {
    getline(cin, tmp);

    if (tmp != "-1")
      v.push_back(tmp);

  } while (tmp != "-1");

  print(v);
}

int main() {

  vector<string> names;

  string tmp;

  do {
    input(names);

    cout << "Do you have any more names to input (y or n)? ";
    cin >> tmp;

  } while (tmp == "y");

  return 0;
}

For non-C++, Java, C users, the error is in print()s for statement.  It should be for (int i = 0; i < names.size(); i++).  This is an easy error to make and overlook (until you get the compiler message) because it is only 1 character and because the >= operator is sometimes required in for loops.

Dunno, spotted it right at the beginning of reading. Maybe would be better to put print() somewhere later in code, so that the reader would get a bit tired before coming to the mistake :)


text:
Convert integer to balanced dozenal
Create a function which takes an integer and returns an array of integers representing the number in balanced base twelve. Specifically, the representation should follow these rules regarding 6 & -6 (from the above link):

If the last digit of a number could be written with either 6 or ϑ, we use the one whose sign is opposite the sign of the first digit. For example, we write decimal 30 as dozenal 3ϑ, but decimal -30 as as dozenal ε6, not ζϑ.
If a 6 or ϑ occurs before the last digit of a number, we use the one whose sign is opposite the next digit after it. For example, we write decimal 71 as dozenal 6τ, but decimal 73 as as dozenal 1ϑ1, not 61.
If a 6 or ϑ is followed by a 0, we keep looking to the right until we can apply one of the first two rules. For example, we write decimal -72 as dozenal τ60, not ϑ0.

Otherwise, the only restrictions are to use only digits in [-6..6], and for the output, when interpreted as big-endian base twelve, to be equivalent to the input.
Example of use:
f(215) => [1,6,-1]
f(216) => [2,-6,0]
f(-82) => [-1,5,2]
f(0)   => [0]

Winner is the shortest, with upvotes being the tiebreaker.

GolfScript, 69 53 49 characters
[.0<\{.12:^%.3$5+>{^-\^+\}*@1$.0<@if@^/.}do;;]-1%

GolfScript expression which takes top of the stack and replaces it by the result. You can play with the code online.

Working on a different solution which should be much shorter - but unfortunately doesn't work for several corner cases...

J, 74 72 characters
Here's my J implementation (f =. not included in character count):
f =. **}.^:(*@#*0={.)@([:((12-~[),0>:@{.@]`[`]}])`,@.(6>[)/&.|.0,12&#.^:_1)@|

And some tests (each result is boxed, and underscore means negative):
   NB. Integers [-10..10]:
   (<@f"0)i:10
┌────┬────┬────┬────┬────┬──┬──┬──┬──┬──┬─┬─┬─┬─┬─┬─┬────┬────┬────┬────┬────┐
│_1 2│_1 3│_1 4│_1 5│_1 6│_5│_4│_3│_2│_1│0│1│2│3│4│5│1 _6│1 _5│1 _4│1 _3│1 _2│
└────┴────┴────┴────┴────┴──┴──┴──┴──┴──┴─┴─┴─┴─┴─┴─┴────┴────┴────┴────┴────┘
   NB. Some boundary values:
   (<@f"0)215 216 217 71 72 73
┌──────┬──────┬──────┬────┬──────┬──────┐
│1 6 _1│2 _6 0│2 _6 1│6 _1│1 _6 0│1 _6 1│
└──────┴──────┴──────┴────┴──────┴──────┘

Interestingly, the rules for 6 have no special place in the function. They work that way just by handling all digits >= 6 together and only working on positive numbers.
I made another version, which doesn't rely on #.^:_1, but it's longer:
**_2&([:}.^:(0={.)+/\)@(((<.@%&12,(1,-&12)`(0,])@.(6>])@(12&|))@{.,}.)^:(0~:{.)^:_)@(,&0)@|

APL(NARS), 71 chars, 142 bytes
{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}

test:
  z←{⍵=0:,0⋄⍵{⍵=0:⍬⋄((m+⍺×m=0)∇⌊12÷⍨⍵+q),m←t-q←12×(6<t)+(⍺>0)×6=t←12∣⍵}⍨×⍵}
  ⎕fmt z¨215 216 ¯82 0 30 ¯30 71 72 73 ¯72
┌10──────────────────────────────────────────────────────────────────────────────────────┐
│┌3──────┐ ┌3──────┐ ┌3──────┐ ┌1─┐ ┌2────┐ ┌2────┐ ┌2────┐ ┌3──────┐ ┌3──────┐ ┌3──────┐│
││ 1 6 ¯1│ │ 2 ¯6 0│ │ ¯1 5 2│ │ 0│ │ 3 ¯6│ │ ¯3 6│ │ 6 ¯1│ │ 1 ¯6 0│ │ 1 ¯6 1│ │ ¯1 6 0││
│└~──────┘ └~──────┘ └~──────┘ └~─┘ └~────┘ └~────┘ └~────┘ └~──────┘ └~──────┘ └~──────┘2
└∊───────────────────────────────────────────────────────────────────────────────────────┘

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/