Skip to content

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

@oittaa

Description

@oittaa

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);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions