Catalan numbers/Pascal's triangle: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m →Composition of pure functions: use wiki markup for links |
|||
Line 2,211:
</pre>
=={{header|Zig}}==
Uses comptime functionality to compile Pascal's triangle into the object code, then at runtime, it's simply a table lookup. (uses code from AKS primality task.)
<lang Zig>
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
pub fn main() !void {
var n: u32 = 1;
while (n <= 15) : (n += 1) {
const row = binomial(n*2).?;
try stdout.print("{d:2} {d:8}\n", .{ n, row[n] - row[n+1] });
}
}
pub fn binomial(n: u32) ?[]const u64 {
if (n >= rmax)
return null
else {
const k = n * (n + 1) / 2;
return pascal[k .. k + n + 1];
}
}
const rmax = 68;
const pascal = build: {
@setEvalBranchQuota(100_000);
var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;
coefficients[0] = 1;
var j: u32 = 0;
var k: u32 = 1;
var n: u32 = 1;
while (n < rmax) : (n += 1) {
var prev = coefficients[j .. j + n];
var next = coefficients[k .. k + n + 1];
next[0] = 1;
var i: u32 = 1;
while (i < n) : (i += 1)
next[i] = prev[i] + prev[i - 1];
next[i] = 1;
j = k;
k += n + 1;
}
break :build coefficients;
};
</lang>
{{Out}}
<pre>
1 1
2 2
3 5
4 14
5 42
6 132
7 429
8 1430
9 4862
10 16796
11 58786
12 208012
13 742900
14 2674440
15 9694845
</pre>
=={{header|zkl}}==
{{trans|PARI/GP}} using binomial coefficients.
|