| author | |
| committer | |
| log | c1db72cdbcddb59aa4e9960f4c07de9781b296f6 |
| tree | 390e143369e9193dfe9cfbf1399623ee8f1700f1 |
| parent | 9f8d938d3825bd5d4d2d7f76907075d13b04d8e1 |
| signature |
2 files changed, 31 insertions(+), 0 deletions(-)
lib/std/math.zig+2| ... | @@ -235,6 +235,7 @@ pub const sinh = @import("math/sinh.zig").sinh; | ... | @@ -235,6 +235,7 @@ pub const sinh = @import("math/sinh.zig").sinh; |
| 235 | pub const cosh = @import("math/cosh.zig").cosh; | 235 | pub const cosh = @import("math/cosh.zig").cosh; |
| 236 | pub const tanh = @import("math/tanh.zig").tanh; | 236 | pub const tanh = @import("math/tanh.zig").tanh; |
| 237 | pub const gcd = @import("math/gcd.zig").gcd; | 237 | pub const gcd = @import("math/gcd.zig").gcd; |
| 238 | pub const lcm = @import("math/lcm.zig").lcm; | ||
| 238 | pub const gamma = @import("math/gamma.zig").gamma; | 239 | pub const gamma = @import("math/gamma.zig").gamma; |
| 239 | pub const lgamma = @import("math/gamma.zig").lgamma; | 240 | pub const lgamma = @import("math/gamma.zig").lgamma; |
| 240 | 241 | ||
| ... | @@ -395,6 +396,7 @@ test { | ... | @@ -395,6 +396,7 @@ test { |
| 395 | _ = cosh; | 396 | _ = cosh; |
| 396 | _ = tanh; | 397 | _ = tanh; |
| 397 | _ = gcd; | 398 | _ = gcd; |
| 399 | _ = lcm; | ||
| 398 | _ = gamma; | 400 | _ = gamma; |
| 399 | _ = lgamma; | 401 | _ = lgamma; |
| 400 | 402 |
lib/std/math/lcm.zig created+29| ... | @@ -0,0 +1,29 @@ | ||
| 1 | //! Least common multiple (https://mathworld.wolfram.com/LeastCommonMultiple.html) | ||
| 2 | const std = @import("std"); | ||
| 3 | |||
| 4 | /// Returns the least common multiple (LCM) of two integers (`a` and `b`). | ||
| 5 | /// For example, the LCM of `8` and `12` is `24`, that is, `lcm(8, 12) == 24`. | ||
| 6 | /// If any of the arguments is zero, then the returned value is 0. | ||
| 7 | pub fn lcm(a: anytype, b: anytype) @TypeOf(a, b) { | ||
| 8 | // Behavior from C++ and Python | ||
| 9 | // If an argument is zero, then the returned value is 0. | ||
| 10 | if (a == 0 or b == 0) return 0; | ||
| 11 | return @abs(b) * (@abs(a) / std.math.gcd(@abs(a), @abs(b))); | ||
| 12 | } | ||
| 13 | |||
| 14 | test lcm { | ||
| 15 | const expectEqual = std.testing.expectEqual; | ||
| 16 | |||
| 17 | try expectEqual(lcm(0, 0), 0); | ||
| 18 | try expectEqual(lcm(1, 0), 0); | ||
| 19 | try expectEqual(lcm(-1, 0), 0); | ||
| 20 | try expectEqual(lcm(0, 1), 0); | ||
| 21 | try expectEqual(lcm(0, -1), 0); | ||
| 22 | try expectEqual(lcm(7, 1), 7); | ||
| 23 | try expectEqual(lcm(7, -1), 7); | ||
| 24 | try expectEqual(lcm(8, 12), 24); | ||
| 25 | try expectEqual(lcm(-23, 15), 345); | ||
| 26 | try expectEqual(lcm(120, 84), 840); | ||
| 27 | try expectEqual(lcm(84, -120), 840); | ||
| 28 | try expectEqual(lcm(1216342683557601535506311712, 436522681849110124616458784), 16592536571065866494401400422922201534178938447014944); | ||
| 29 | } | ||