Would like to get some help regarding this algorithm. Can’t figure out what I’m doing wrong here. Added comments to clarify what I was trying to do. For further clarification, please feel free to ask. Thanks.
// function for the greatest common divisor for two numbers
let gcd_two_numbers = (n1, n2) => {
while (n1 != n2) {
if (n1 > n2) {
n1 = n1 - n2;
} else {
n2 = n2 - n1;
}
}
return n2;
};
// function for the greatest common divisor for more than two numbers
let gcd = (arr) => {
return arr.reduce((a, b) => {
return gcd_two_numbers(a, b);
});
};
function smallestCommons(arr) {
// sorted the array from largest to smallest number
arr.sort((a, b) => b - a);
let range = [];
// inserted all the numbers between largest and smallest number, excluding 1.
for(let i = arr[0]; i >= arr[1]; i--) {
if (i > 1) {
range.push(i);
}
}
// multiplied all the numbers in the range array
let multiple = range.reduce((a, b) => a * b);
// to find the smallest common multiple, divided multiple of all numbers in the range array with the greatest common divisor of all the numbers in the range array.
let lcm = multiple / gcd(range);
return lcm;
}
smallestCommons([1,5]); // should return 60