JavaScript Program to Find LCM of Two Numbers using a Loop
In this approach, we are using a loop to find the LCM of two numbers. Starting from the larger number, it increments by that value until it finds a multiple that is divisible by the smaller number, resulting in the LCM
Syntax:
function lcmFunction(a, b) {
let larger = Math.max(a, b);
let smaller = Math.min(a, b);
for (let i = larger; ; i += larger) {
if (i % smaller === 0) {
return i;
}
}
};
Example: In this example, we are using the above-explained approach.
Javascript
function lcmFunction(a, b) { let larger = Math.max(a, b); let smaller = Math.min(a, b); for (let i = larger; ; i += larger) { if (i % smaller === 0) { return i; } } } let num1 = 12; let num2 = 18; let result = lcmFunction(num1, num2); console.log(`LCM of ${num1} and ${num2} is ${result}`); |
LCM of 12 and 18 is 36
JavaScript Program to Find LCM of Two Numbers
In this article, we are going to learn about finding the LCM of two numbers by using JavaScript. LCM (Least Common Multiple) of two numbers is the smallest positive integer that is divisible by both numbers without leaving a remainder. It’s a common multiple of the numbers.
LCM of two numbers = Product of two numbers ÷ HCF of two numbers.
LCM(a, b) = (a * b) / GCD(a, b)
Where GCD(a, b) represents the Greatest Common Divisor of the two numbers.
Example:
Numbers : 12 and 80
prime factors of each
12: 2 × 2 × 3
80: 2 × 2 × 2 × 2 × 5 (2: 4 times,3: 1 time,5: 1 time)
Multiply each factor the maximum number of times it occurs in either number.
2 x 2 x 2 x 2 x 3 x 5 =240 ( 240 is the lowest number that can be divided by both 12 and 80.)
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
- Using the Formula (a * b) / GCD(a, b)
- Without using the formula
- Using a Loop
We will explore all the above methods along with their basic implementation with the help of examples.