<html><head></head>
<body><script>
function calculateGreatestCommonDivisor(a, b) {
if (a == 0) {
return b;
}
return calculateGreatestCommonDivisor(b % a, a);
}
function getDifference(array) {
for (var i = Math.min(...array) + 1; i < Math.max(...array); i++) {
array.push(i);
}
array.sort((a, b) => a - b);
}
function findSmallestCommonMultiple(arr) {
getDifference(arr);
console.log(arr);
a = arr[arr.length - 1];
b = arr[arr.length - 2];
var LCM = a * b / calculateGreatestCommonDivisor(a, b);
while (true) {
var index = arr.findIndex(element => LCM % element !== 0);
if (index === -1) {
return LCM;
}
LCM *= arr[index];
console.log(LCM);
}
}
findSmallestCommonMultiple([1, 5]) // correct
findSmallestCommonMultiple([2, 10]) // correct
findSmallestCommonMultiple([1, 13]) // incorrect
findSmallestCommonMultiple([23, 18]) // incorrect
</script></body>
</html>
This code is part of a challenge which can be found at:
Here is the algorithm I am using:
1- Calculate the Least Common Multiple (LCM) of the two greatest numbers in the array.
2- Divide the LCM by each number in the array until you find one that doesn't divide evenly. Multiply that number with LCM and repeat the process until no such number is found. Then return the LCM.
While the code works correctly for the first two arrays, it fails for the last two arrays. I am wondering if my algorithm is fundamentally flawed and needs a complete rewrite or if it just requires some adjustments?
It's important to note that there are three separate functions in the code: one for calculating the Greatest Common Divisor (GCD), another for finding the range of values between two numbers in the array, and the third for calculating the LCM.
The issue arises with the last two arrays:
findSmallestCommonMultiple([1, 13]) returns 4324320 instead of 360360
findSmallestCommonMultiple([23, 18]) returns 72681840 instead of 6056820
Therefore, I am seeking advice on whether my algorithm needs a complete overhaul or if minor tweaks can make it work as intended.
Please refrain from providing ready-made codes and simply offer insights on my specific query. Thank you (: