Problem
Design an efficient algorithm for computing c(n, k) that has the property that it never overflows if c(n, k) can be represented as an integer assume n and k are both integers.
Solution
using System;
namespace BinomialCoefficients
{
class Program
{
static int NChooseK(int n, int k)
{
if (n == k || k == 0)
{
return 1;
}
return NChooseK(n - 1, k) + NChooseK(n - 1, k - 1);
}
static void Main(string[] args)
{
for (int n = 1; n < 20; n++)
{
Console.WriteLine("-----------------------------------------------");
for (int k = 0; k <= n; k++)
{
Console.WriteLine("({0, 2}, {1, 2}) = {2, 10}", n, k, NChooseK(n, k));
}
}
}
}
}
Output
-----------------------------------------------
( 1, 0) = 1
( 1, 1) = 1
-----------------------------------------------
( 2, 0) =