Catalan numbers: Difference between revisions

Content added Content deleted
(Updated D entry)
Line 891: Line 891:
<lang d>import std.stdio, std.bigint, std.functional;
<lang d>import std.stdio, std.bigint, std.functional;


BigInt factorial(uint n) {
BigInt factorial(in uint n) {
alias memoize!factorial mfact;
alias mfact = memoize!factorial;
return n ? mfact(n - 1) * n : BigInt(1);
return n ? mfact(n - 1) * n : 1.BigInt;
}
}


auto cats1(uint n) {
auto cats1(in uint n) {
return factorial(2 * n) / (factorial(n + 1) * factorial(n));
return factorial(2 * n) / (factorial(n + 1) * n.factorial);
}
}


BigInt cats2(uint n) {
BigInt cats2(in uint n) {
alias memoize!cats2 mcats2;
alias mcats2 = memoize!cats2;
if (n == 0) return BigInt(1);
if (n == 0) return 1.BigInt;
auto sum = BigInt(0);
BigInt sum = 0;
foreach (i; 0 .. n)
foreach (immutable i; 0 .. n)
sum += mcats2(i) * mcats2(n - 1 - i);
sum += mcats2(i) * mcats2(n - 1 - i);
return sum;
return sum;
}
}


BigInt cats3(uint n) {
BigInt cats3(in uint n) {
alias memoize!cats3 mcats3;
alias mcats3 = memoize!cats3;
return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : BigInt(1);
return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : 1.BigInt;
}
}


void main() {
void main() {
foreach (i; 0 .. 15)
foreach (immutable i; 0 .. 15)
writefln("%2d => %s %s %s", i, cats1(i), cats2(i), cats3(i));
writefln("%2d => %s %s %s", i, i.cats1, i.cats2, i.cats3);
}</lang>
}</lang>
{{out}}
{{out}}