Code Golf: Number of paths!

PARI GP

binomial(2*n,n)

Mathematica

Binomial[2n, n]

C# (203 chars)

using System;using i=System.Numerics.BigInteger;class X{static void Main(){Func<i,i>f=null;f=n=>n<2?1:n*f(n-1);try{i p=i.Parse(Console.In.ReadLine());Console.WriteLine(f(2*p)/f(p)/f(p));Main();}catch{}}}

Readable:

using System;
using i = System.Numerics.BigInteger;
class X
{
    static void Main()
    {
        Func<i, i> f = null;
        f = n => n < 2 ? 1 : n * f(n - 1);
        try
        {
            i p = i.Parse(Console.In.ReadLine());
            Console.WriteLine(f(2 * p) / f(p) / f(p));
            Main();
        }
        catch { }
    }
}

Tricks I used:

  • Using try/catch instead of an explicit end condition for the main loop

  • Calling Main() recursively is slightly shorter than for(;;){...} or x:...goto x;


Ruby, 48 characters

#!ruby -n
s=1;1.upto(l=$_.to_i){|a|s+=s*l/a};p s

Tags:

Math

Code Golf