Polyglot Factorial

November 16, 2011 Glenn Jahnke

Someone on Hacker News mentioned the number of orderings of a deck of cards. I took up the challenge in some of my favorite and not so favorite languages, I’ll let you guess :).

Ruby

ruby-1.9.2-p180> (1..52).inject{|a,b|a*b}
=>
80658175170943878571660636856403766975289505440883277824000000000000

Scala

scala> BigInt(1).to(BigInt(52)).toList.foldLeft(BigInt(1))((a,b) => a*b)
res23: scala.math.BigInt =>
80658175170943878571660636856403766975289505440883277824000000000000

Haskell

Prelude> foldl1 (x -> y -> x*y) [1..52]
80658175170943878571660636856403766975289505440883277824000000000000

CoffeeScript

coffee> [1..52].reduce (a,b) -> a*b

8.065817517094388e+67

Java

Non-existent REPL>
import java.math.*;
public class Factorial {
public static void main(String[] args) {
BigInteger result = BigInteger.ONE;
BigInteger fiftyTwo = new BigInteger(”52″);
for(BigInteger i = BigInteger.ONE; i.compareTo(fiftyTwo) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
System.out.println(result);
}
}

$ java Factorial
80658175170943878571660636856403766975289505440883277824000000000000

** I could have used the product function in most of those examples, but I wanted to play with foldL ;)

About the Author

Biography

More Content by Glenn Jahnke
Previous
Too many parentheses
Too many parentheses

Cedar comes with its own built-in matcher library and here is Adam Milligan's blog post that explains on ho...

Next
With over 100,000,000 test runs, Speedtest for PlayBook is live!
With over 100,000,000 test runs, Speedtest for PlayBook is live!

With over 100,000,000 tests runs to date, the Xtreme Labs Speedtest app has made the transition to the Blac...

Enter curious. Exit smarter.

Learn More