You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It would be nice to have an official least common multiple (LCM) implementation in the math library. I saw that the crypto module has implemented it, but maybe a better place would be in the math module?
It could be something like the following and being functionally similar with other popular languages. If a zero is passed, many popular programming languages return zero in those cases.
conststd=@import("std");
pubfnlcm(a: anytype, b: anytype) @TypeOf(a, b) {
// Behavior from C++ and Python// If an argument is zero, then the returned value is 0.if (a==0orb==0) return0;
return@abs(b) * (@abs(a) /std.math.gcd(@abs(a), @abs(b)));
}
testlcm {
constexpectEqual=std.testing.expectEqual;
tryexpectEqual(lcm(0, 0), 0);
tryexpectEqual(lcm(1, 0), 0);
tryexpectEqual(lcm(-1, 0), 0);
tryexpectEqual(lcm(0, 1), 0);
tryexpectEqual(lcm(0, 1), 0);
tryexpectEqual(lcm(7, 1), 7);
tryexpectEqual(lcm(7, -1), 7);
tryexpectEqual(lcm(-23, 15), 345);
tryexpectEqual(lcm(120, 84), 840);
tryexpectEqual(lcm(84, -120), 840);
}
I would've liked to put @abs just around the whole result value, but gcd didn't like negative values:
/opt/homebrew/Cellar/zig/0.13.0/lib/zig/std/math/gcd.zig:14:29: note: called from here
std.debug.assert(b >= 0);
The text was updated successfully, but these errors were encountered:
It would be nice to have an official least common multiple (LCM) implementation in the math library. I saw that the crypto module has implemented it, but maybe a better place would be in the math module?
It could be something like the following and being functionally similar with other popular languages. If a zero is passed, many popular programming languages return zero in those cases.
I would've liked to put
@abs
just around the whole result value, butgcd
didn't like negative values:The text was updated successfully, but these errors were encountered: