JavaScript: Least common multiple (LCM) of two numbers
JavaScript Math: Exercise-10 with Solution
Write a JavaScript function to get the least common multiple (LCM) of two numbers.
Note :
According to Wikipedia - A common multiple is a number that is a multiple of two or more integers. The common multiples of 3 and 4 are 0, 12, 24, .... The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both.
Test Data:
console.log(lcm_two_numbers(3,15));
console.log(lcm_two_numbers(10,15));
Output :
15
30
Explanation of L.C.M.:

Pictorial Presentation of L.C.M. of two numbers:
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>LCM of two numbers</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function lcm_two_numbers(x, y) {
if ((typeof x !== 'number') || (typeof y !== 'number'))
return false;
return (!x || !y) ? 0 : Math.abs((x * y) / gcd_two_numbers(x, y));
}
function gcd_two_numbers(x, y) {
x = Math.abs(x);
y = Math.abs(y);
while(y) {
var t = y;
y = x % y;
x = t;
}
return x;
}
console.log(lcm_two_numbers(3,15));
console.log(lcm_two_numbers(10,15));
Sample Output:
15 30
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-10 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript function to find the GCD (greatest common divisor) of more than 2 integers.
Next: Write a JavaScript function to get the least common multiple (LCM) of more than 2 integers.
What is the difficulty level of this exercise?
JavaScript: Tips of the Day
JavaScript: Using length to resize an array
You can either resize or empty an array.
var array = [11, 12, 13, 14, 15]; console.log(array.length); // 5 array.length = 3; console.log(array.length); // 3 console.log(array); // [11,12,13] array.length = 0; console.log(array.length); // 0 console.log(array); // []
Ref: https://bit.ly/3nWPRDJ
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework
