跳转到内容
标准库Zig 0.17.1官方原文
源码std/math/lcm.zig

第 1 行

最小公倍数(https://mathworld.wolfram.com/LeastCommonMultiple.html)

std.math.lcm.lcm

函数

第 7 行

返回两个整数(a 和 b)的最小公倍数(LCM)。 例如,8 和 12 的最小公倍数为 24,即 lcm(8, 12) == 24。 若任一参数为零,则返回 0。

pub fn lcm(a: anytype, b: anytype) @TypeOf(a, 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(8, 12), 24);
    try expectEqual(lcm(-23, 15), 345);
    try expectEqual(lcm(120, 84), 840);
    try expectEqual(lcm(84, -120), 840);
    try expectEqual(lcm(1216342683557601535506311712, 436522681849110124616458784), 16592536571065866494401400422922201534178938447014944);
}

std.math.lcm.std

别名

第 2 行

别名目标 std

源码

std/math/lcm.zig

//! 最小公倍数(https://mathworld.wolfram.com/LeastCommonMultiple.html)
const std = @import("std");

/// 返回两个整数(`a` 和 `b`)的最小公倍数(LCM)。
/// 例如,`8` 和 `12` 的最小公倍数为 `24`,即 `lcm(8, 12) == 24`。
/// 若任一参数为零,则返回 0。
pub fn lcm(a: anytype, b: anytype) @TypeOf(a, b) {
    // C++ 和 Python 的行为
    // 若参数为零,则返回值为 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(8, 12), 24);
    try expectEqual(lcm(-23, 15), 345);
    try expectEqual(lcm(120, 84), 840);
    try expectEqual(lcm(84, -120), 840);
    try expectEqual(lcm(1216342683557601535506311712, 436522681849110124616458784), 16592536571065866494401400422922201534178938447014944);
}