Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

lcm

Calculates the least common multiple (LCM) of two integers.

Note: This utility uses another utility: gcd
TypeScript
Copied!
1/**
2 * Calculates the least common multiple (LCM) of two integers.
3 *
4 * @param a - First integer
5 * @param b - Second integer
6 * @returns The least common multiple of a and b, or 0 if either input is 0
7 * @throws If inputs are not finite integers
8 */
9export function lcm(a: number, b: number): number {
10  if (!Number.isInteger(a) || !Number.isInteger(b)) {
11    throw new Error('Inputs must be integers');
12  }
13
14  if (a === 0 || b === 0) return 0;
15
16  return Math.abs(a * b) / gcd(a, b);
17}
  • Input Validation

    Ensures both values are finite integers, reducing the chance of invalid usage or unexpected results.

  • Handles Zero Gracefully

    Correctly returns 0 if either input is zero, aligning with the mathematical definition of LCM.

  • Builds on Reusable Logic

    Reuses the gcd function internally for an efficient and elegant implementation of LCM.

  • Compact and Performant

    Performs minimal operations using multiplication and division for fast execution.

Tests | Examples

TypeScript
Copied!
1test('lcm - basic case', () => {
2  expect(lcm(4, 6)).toBe(12);
3});
4
5test('lcm - one is multiple of the other', () => {
6  expect(lcm(5, 20)).toBe(20);
7});
8
9test('lcm - same numbers', () => {
10  expect(lcm(7, 7)).toBe(7);
11});
12
13test('lcm - one is zero', () => {
14  expect(lcm(0, 10)).toBe(0);
15  expect(lcm(10, 0)).toBe(0);
16});
17
18test('lcm - negative inputs', () => {
19  expect(lcm(-3, 5)).toBe(15);
20  expect(lcm(3, -5)).toBe(15);
21  expect(lcm(-3, -5)).toBe(15);
22});
23
24test('lcm - throws on non-integer', () => {
25  expect(() => lcm(2.5, 3)).toThrow('Inputs must be integers');
26  expect(() => lcm(3, NaN)).toThrow('Inputs must be integers');
27});

Common Use Cases

  • Scheduling and Task Alignment

    Find synchronization intervals for events or processes with different frequencies.

  • Fraction Denominator Normalization

    Compute a common denominator when adding or comparing fractions.

  • Signal Processing or Sampling

    Determine when signals or intervals will align in time-based systems.

  • Grid and Layout Calculations

    Calculate least common tile sizes or snapping grids for graphical or UI applications.

  • Mathematics and Educational Tools

    Teach and demonstrate number theory principles like divisibility, factorization, and multiples.

Codebase: Utilities -> Numbers -> lcm | Yevhen Klymentiev