find the least common multiple of two numbers in typescript

To find the least common multiple (LCM) of two numbers, you can use the Euclidean algorithm, which involves finding the greatest common divisor (GCD) of the two numbers.

Here's the TypeScript code to find the LCM of two numbers using the Euclidean algorithm:

index.ts
function gcd(a: number, b: number): number {
  if (b === 0) {
    return a;
  }
  return gcd(b, a % b);
}

function lcm(a: number, b: number): number {
  return (a * b) / gcd(a, b);
}
184 chars
11 lines

We define a function gcd that recursively finds the GCD of two numbers using the modulo operator. Then we define a function lcm that finds the product of the two numbers and divides it by their GCD to get the LCM.

You can call the lcm function with your two numbers as arguments:

index.ts
const num1 = 12;
const num2 = 18;
const result = lcm(num1, num2);
console.log(`The LCM of ${num1} and ${num2} is ${result}`);
// Output: The LCM of 12 and 18 is 36
164 chars
6 lines

gistlibby LogSnag