Python's math.lcm in TypeScript

✓ Verified: Python 3.12
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { lcm } from 'locutus/python/math/lcm'.

Or with CommonJS: const { lcm } = require('locutus/python/math/lcm')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1lcm(12, 18)36
2lcm(4, 6, 8)24
3lcm(5, 0)0

Notes

  • Returns least common multiple for all provided integer values.

Here's what our current TypeScript equivalent to Python's math.lcm looks like.

const gcdPair = (a: number, b: number): number => {
let left = Math.abs(a)
let right = Math.abs(b)

while (right !== 0) {
const temp = right
right = left % right
left = temp
}

return left
}

export function lcm(...values: Array<number | string>): number {
// discuss at: https://locutus.io/python/lcm/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns least common multiple for all provided integer values.
// example 1: lcm(12, 18)
// returns 1: 36
// example 2: lcm(4, 6, 8)
// returns 2: 24
// example 3: lcm(5, 0)
// returns 3: 0

if (values.length === 0) {
return 1
}

let result = Math.trunc(Number(values[0] ?? 0))
if (!Number.isFinite(result)) {
throw new TypeError('lcm(): values must be finite integers')
}

for (let index = 1; index < values.length; index += 1) {
const raw = values[index]
const next = Math.trunc(Number(raw))
if (!Number.isFinite(next)) {
throw new TypeError('lcm(): values must be finite integers')
}
if (result === 0 || next === 0) {
result = 0
continue
}
result = Math.abs((result / gcdPair(result, next)) * next)
}

return Math.abs(result)
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 34 Python functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python math functions


Star