diff options
| author | oittaa <8972248+oittaa@users.noreply.github.com> | 2025-03-24 16:07:40 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-03-24 16:07:40 +0100 |
| commit | c1db72cdbcddb59aa4e9960f4c07de9781b296f6 (patch) | |
| tree | 390e143369e9193dfe9cfbf1399623ee8f1700f1 /lib/std/math/lcm.zig | |
| parent | 9f8d938d3825bd5d4d2d7f76907075d13b04d8e1 (diff) | |
| download | zig-c1db72cdbcddb59aa4e9960f4c07de9781b296f6.tar.gz zig-c1db72cdbcddb59aa4e9960f4c07de9781b296f6.zip | |
std.math: Add least common multiple (lcm)
Diffstat (limited to 'lib/std/math/lcm.zig')
| -rw-r--r-- | lib/std/math/lcm.zig | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/std/math/lcm.zig b/lib/std/math/lcm.zig new file mode 100644 index 0000000000..8187102a6e --- /dev/null +++ b/lib/std/math/lcm.zig @@ -0,0 +1,29 @@ +//! Least common multiple (https://mathworld.wolfram.com/LeastCommonMultiple.html) +const std = @import("std"); + +/// Returns the least common multiple (LCM) of two integers (`a` and `b`). +/// For example, the LCM of `8` and `12` is `24`, that is, `lcm(8, 12) == 24`. +/// If any of the arguments is zero, then the returned value is 0. +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(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); +} |
