Question:
This is part of a larger function. I am currently trying to create a helper function to find the highest common factor of two numbers. It will ultimately go into a function that will loop through an array of numbers, find the highest common factor (HCF) and call the HCF function in a function to find the lowest common multiple throughout the entire range. This is step one, so to speak, and I have most of the numbers finding the accurate answer, but it only runs the division part of the function once and doesn’t continue dividing until the remainder is 0 if it needs to divide more than once. Not sure what I’m missing to make that continue to do so until my base case.
function HCF(a, b) {
let max = Math.max(a, b);
let min = Math.min(a, b);
let answer = max % min;
console.log(answer, "this is the first log");
while (max % min !== 0) {
answer = max % min;
let newMin = Math.max(answer, answer = min % answer);
newMin % answer;
console.log(min, newMin, "this is the min log");
console.log(answer, "this is the second log");
}
answer = newMin;
console.log(answer, "this is the third log");
console.log(answer, "this is the fourth log");
return answer;
}
// HCF(1, 5); ***works***
// HCF(2, 10); ***works***
// HCF(72, 60); ***works***
// HCF(148, 48); ***works***
// HCF(130, 78); ***works***
HCF (585, 105); // ***doesn't work***
***Also, I have tried an “if-else” statement in place of that while loop, and it didn’t work out so well…but the while loop is now creating an infinite loop, and I’m not sure why that is either…it doesn’t have a stopping point because it’s not really looping. I feel like the same code I’m missing will work for both the while loop and conditional chain, but still at a loss as to what that may be.
Okay, so just to show the full function, I am sharing the code here. I managed to get the whole monster of a function working!!!
function smallestCommons(arr) {
// helper function that takes the array, sorts it and then creates a range between the numbers passed into the given array
function rangeArr(arr) {
arr.sort((a, b) => a - b);
let arrMax = Math.max(arr[0], arr[1]);
let arrMin = Math.min(arr[0], arr[1]);
let initialRange = [arrMin];
while(arrMin < arrMax) {
initialRange.push(arrMin + 1);
arrMin++
}
return initialRange;
}
let range = rangeArr(arr);
// helper function that finds the highest common factor between two numbers
function HCF(a, b) {
let max = Math.max(a, b);
let min = Math.min(a, b);
let answer = max % min;
while (answer !== 0) {
let newMin = min;
min = answer;
max = newMin;
answer = max % min;
}
return min;
}
// another function that uses the HCF function to find the least common multiple
function LCM(a, b) {
return (a * b) / HCF(a,b);
}
// reduce through the range initilaized to the range variable and apply the LCM function, returning the entire "reduce" code block
return range.reduce((acc, current) => LCM(acc, current));
}