Understood your request clearly.
Below is a straightforward script that accomplishes what you asked for:
//credit to: https://jsfiddle.net/JamesOR/RC7SY/
function getAllFactorsFor(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
function calculate(x) {
lastFactorCount = 0;
highestNumber = 0;
while (x) {
currentCount = getAllFactorsFor(x).length;
if (currentCount > lastFactorCount) {
lastFactorCount = currentCount;
highestNumber = x;
}
x--;
}
return highestNumber;
}
console.log(calculate(7)); //output: 6
console.log(calculate(11)) //output: 8
This code works for the given test cases provided. I used the getAllFactorsFor()
function from an existing jsfiddle as there's no need to start from scratch ;)
The calculate()
function takes an input number, iterates through each number from x down to 0, counts its factors, and stores the number with the most factors count while reducing x in each iteration.
In the end, it returns the number with the highest factor count. Simple as that.
Hope this solution proves beneficial!