Stirling Numbers (Type 1)

Stirling's Numbers of the First Form calculate the number of permutations of the sequence {1,2,3...n} into k distinct cycles.

The recurrence is given by:

f(n,k) = [n-1]*f(n-1,k)+f(n-1,k-1)

With the following base cases:

f(1,1) = f(n,n) = 1 f(n,1) = (n-1)! f(0,0) = 1 f(n,0) = 0

Java is clearly the language of choice for this method, as Java has the BigInteger class. I have had success for up to n=400 and k = 200 without a TLE; much over that will likely TLE. F(400,200) has 571 digits.

Java
static BigInteger DP[][] ; static BigInteger FACT[] ; public static BigInteger St1(int n, int k)   { if (n == k)           return BigInteger.ONE ; if (k == 1) {           return FACT[n-1] ; }       if (DP[n][k] != null) {           return DP[n][k] ; }       BigInteger tem = BigInteger.valueOf(n-1) ; tem = tem.multiply(St1(n-1,k)) ; tem = tem.add(St1(n-1,k-1)); return DP[n][k] = tem ; }   public static void main(String[] args) {       Scanner input = new Scanner(System.in) ; DP = new BigInteger[1000][1000] ; FACT = new BigInteger[1000] ; FACT[0] = BigInteger.ONE ; for (int i = 1 ; i < 1000 ; i ++) {           FACT[i] = FACT[i-1].multiply(BigInteger.valueOf(i)) ; }        int N = input.nextInt ; int K = input.nextInt ; System.out.println(St1(N,K)); }