1. Introduction
The Least Common Multiple (LCM) of two numbers is the smallest multiple that is divisible by both numbers. In this post, we will design a TypeScript program to find the LCM of two numbers. One efficient way to determine the LCM is by using the relation between the LCM and the Greatest Common Divisor (GCD) of two numbers: LCM(a, b) = (a * b) / GCD(a, b).
2. Program Overview
The program starts by calculating the GCD of the two numbers using the Euclidean algorithm. It then determines the LCM using the formula mentioned above.
3. Code Program
// Function to compute the GCD of two numbers
function gcd(a: number, b: number): number {
if (b === 0) return a;
return gcd(b, a % b);
}
// Function to compute the LCM of two numbers
function lcm(a: number, b: number): number {
return (a * b) / gcd(a, b);
}
// Test the function
const num1 = 12;
const num2 = 15;
const result = lcm(num1, num2);
console.log(`The LCM of ${num1} and ${num2} is:`, result);
Output:
The LCM of 12 and 15 is: 60
4. Step By Step Explanation
1. We start by defining a function gcd that computes the Greatest Common Divisor of two numbers. This function uses the Euclidean algorithm.
2. Next, we define the lcm function. Inside it, we use the relationship between the LCM and GCD to calculate the LCM.
3. To calculate the LCM of two numbers, we multiply them together and then divide by their GCD.
4. We then test the lcm function using two numbers, 12 and 15 and print the result.
5. The program determines that the least common multiple of 12 and 15 is 60, which is the correct result.
Comments
Post a Comment
Leave Comment