swift-numerics icon indicating copy to clipboard operation
swift-numerics copied to clipboard

Add Least Common Multiple

Open jasonbobier opened this issue 4 months ago • 5 comments

This is an enhancement request to add least common multiple to the package. A major issue with least common multiple is that it is not uncommon for it to overflow when used with fixed width integers. This PR offers two functions, one that traps and one that throws should the result not be representable in its result type.

The code changes are in this PR: https://github.com/jasonbobier/swift-numerics/pull/1

It currently is waiting on the resolution of https://github.com/apple/swift-numerics/pull/320 and then the base will be switched to apple/numerics.

jasonbobier avatar Aug 19 '25 14:08 jasonbobier

My two cents here (as with gcd) would be that a "reporting overflow" version would be more consistent with how the stdlib reports overflow and (if desired) a double-width version would cover our bases completely.

xwu avatar Aug 19 '25 14:08 xwu

Weren't the stdlib patterns created before error handling was added to the language though? Also afaik, the overflow patterns are only used as single (almost always) instruction overflow bit status tests, whereas calling lcm() again requires an entire gcd() pass. This might be an issue for rational numbers on embedded systems.

Note that I'm not necessarily against the overflow, double-width solution. I was just thinking about saving the extra gcd() once this starts to be used with rational numbers which overflow fairly often.

jasonbobier avatar Aug 19 '25 15:08 jasonbobier

Weren't the stdlib patterns created before error handling was added to the language though?

No, long after.

xwu avatar Aug 19 '25 15:08 xwu

Yeah, thinking about it, I can think of good use cases for leastCommonMultipleReportingOverflow and leastCommonMultipleFullWidth as well, so I'll add those too.

jasonbobier avatar Aug 19 '25 20:08 jasonbobier

OK, added leastCommonMultipleReportingOverflow and leastCommonMultipleFullWidth along with associated tests.

jasonbobier avatar Aug 20 '25 15:08 jasonbobier