Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add math/lcm (least common multiple) function #22660

Open
oittaa opened this issue Jan 29, 2025 · 0 comments · May be fixed by #22661
Open

Add math/lcm (least common multiple) function #22660

oittaa opened this issue Jan 29, 2025 · 0 comments · May be fixed by #22661

Comments

@oittaa
Copy link

oittaa commented Jan 29, 2025

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.

const std = @import("std");

pub fn lcm(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 == 0 or b == 0) return 0;
    return @abs(b) * (@abs(a) / std.math.gcd(@abs(a), @abs(b)));
}

test lcm {
    const expectEqual = std.testing.expectEqual;

    try expectEqual(lcm(0, 0), 0);
    try expectEqual(lcm(1, 0), 0);
    try expectEqual(lcm(-1, 0), 0);
    try expectEqual(lcm(0, 1), 0);
    try expectEqual(lcm(0, 1), 0);
    try expectEqual(lcm(7, 1), 7);
    try expectEqual(lcm(7, -1), 7);
    try expectEqual(lcm(-23, 15), 345);
    try expectEqual(lcm(120, 84), 840);
    try expectEqual(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);
@oittaa oittaa linked a pull request Jan 29, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant