Jump to content

Catalan numbers: Difference between revisions

Updated D entry
(Updated D entry)
Line 891:
<lang d>import std.stdio, std.bigint, std.functional;
 
BigInt factorial(in uint n) {
alias mfact = memoize!factorial mfact;
return n ? mfact(n - 1) * n : BigInt(1).BigInt;
}
 
auto cats1(in uint n) {
return factorial(2 * n) / (factorial(n + 1) * factorial(n).factorial);
}
 
BigInt cats2(in uint n) {
alias mcats2 = memoize!cats2 mcats2;
if (n == 0) return BigInt(1).BigInt;
autoBigInt sum = BigInt(0);
foreach (immutable i; 0 .. n)
sum += mcats2(i) * mcats2(n - 1 - i);
return sum;
}
 
BigInt cats3(in uint n) {
alias mcats3 = memoize!cats3 mcats3;
return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : BigInt(1).BigInt;
}
 
void main() {
foreach (immutable i; 0 .. 15)
writefln("%2d => %s %s %s", i, cats1(i).cats1, cats2(i).cats2, cats3(i).cats3);
}</lang>
{{out}}
Cookies help us deliver our services. By using our services, you agree to our use of cookies.