Golfscript - 56 50 49 48 41 40 38 37 chars
n%{~),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;}/
Note: this handles multiple lines of input, is fast (1/8 secs to do the test cases), and doesn't break for any legal input.
(The first version was also my first ever Golfscript program; thanks to eBusiness for pointing out several tricks I missed).
In order to make this a useful educational post too, here's an explanation of how it works. We start with the recurrence f(n, k) = k * (f(n-1, k) + f(n-1, k-1))
. This can be understood combinatorically as saying that to place n
distinguishable balls in k
distinguishable buckets such that each bucket contains at least one ball, you pick one of the k
buckets for the first ball (k *
) and then either it will contain at least one more ball (f(n-1, k)
) or it won't (f(n-1, k-1)
).
The values resulting from this form a grid; taking n
as the row index and k
as the column index and indexing both from 0 it starts
1 0 0 0 0 0 0 ...
0 1 0 0 0 0 0 ...
0 1 2 0 0 0 0 ...
0 1 6 6 0 0 0 ...
0 1 14 36 24 0 0 ...
0 1 30 150 240 120 0 ...
0 1 62 540 1560 1800 720 ...
. . . . . . . .
. . . . . . . .
. . . . . . . .
So turning to the program,
n%{~ <<STUFF>> }/
splits the input into lines and then for each line evaluates it, putting n
and k
on the stack, and then calls <<STUFF>>
, which is as follows:
),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;
This computes the first k+1
entries of the n+1
th row of that grid. Initially the stack is n k
.
),
gives stack of n [0 1 2 ... k]
{!}%
gives stack of n [1 0 0 ... 0]
where there are k
0s.
\{ <<MORE STUFF>> }*
brings the n
to the top and makes it the number of times we execute <<MORE STUFF>>
.
Our stack currently is a row of the table: [f(i,0) f(i,1) ... f(i,k)]
0.@
puts a couple of 0s before that array. The first one will be j
and the second one will be f(i,j-1)
.
{ <<FINAL LOOP>> }/
loops through the elements of the array; for each one it puts it on top of the stack and then executes the loop body.
.@+2$*@)@
is boring stack manipulation to take ... j f(i,j-1) f(i,j)
and yield ... j*(f(i,j-1)+f(i,j)) j+1 f(i,j)
;;]
pops off the left-over k+1 f(i,k)
and gathers everything into an array, ready for the next go round the loop.
Finally, when we've generated the n
th row of the table,
)p;
takes the last element, prints it, and discards the rest of the row.
For posterity, three 38-char solutions on this principle:
n%{~),{!}%\{0.@{.@+@.@*\)@}/;;]}*)p;}/
n%{~),{!}%\{0:x\{x\:x+1$*\)}/;]}*)p;}/
n%{~),{!}%\{0.@{@1$+2$*\@)}/;;]}*)p;}/
S(n,0)
is1
ifn=0
and0
otherwise). If you want I can find a reference for the stronger statement that Stirling2 is in the associative subgroup of the exponential Riordan group. \$\endgroup\$