Factorial: Difference between revisions
→Zig
imported>MaD70 (→{{header|APL}}: Recursive definition) |
Recombinant (talk | contribs) (→Zig) |
||
Line 10,814:
=={{header|Zig}}==
{{Works with|Zig=0.11.0}}
Supports all integer data types, and checks for both overflow and negative numbers; returns null when there is a domain error.
<syntaxhighlight lang="zig">
pub fn factorial(comptime Num: type, n: i8) ?Num {
return if (@typeInfo(Num) != .Int)
@compileError("factorial called with
else if (n < 0)
null
Line 10,827 ⟶ 10,826:
var fac: Num = 1;
while (i <= n) : (i += 1) {
if (tmp[1] !=
break :calc null; // overflow
fac = tmp[0];
} else break :calc fac;
};
Line 10,834 ⟶ 10,835:
pub fn main() !void {
try stdout.print("0! = {}\n", .{factorial(i32, 0)});▼
try stdout.print("
try stdout.print("
try stdout.print("
try stdout.print("
try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible
}
</syntaxhighlight>
|