Like I did with the Sum All Primes challenge, I freshened up Smallest Common Multiple guide post because some of the solutions were pretty bad from an efficiency standpoint.
If anyone has feedback for these updated solutions, please let me know. I’m sure there are parts I can improve/clarify:
As this is within the JS Algorithms and Data Structures section, and not the Coding Interview Prep section, I think it best to have a first solution without:
for (let i = min; i <= max; i++) {
divisible = divisible && (multiple % i === 0);
}
That is, I do not think this is as friendly as many would like. Yes, Campers could understand it, but many do complain when the first solution is not immediately straightforward with common code (specifically mentioned in the prior lessons)
function smallestCommons(arr) {
// Setup
const [min, max] = arr.sort((a, b) => a - b);
const numberDivisors = max - min + 1;
// Largest possible value for SCM
let upperBound = 1;
for (let i = min; i <= max; i++) {
upperBound *= i;
}
// Test all multiples of 'max'
let multiple = max;
for (multiple = max; multiple <= upperBound; multiple += max) {
// Check if every value in range divides 'multiple'
let divisorCount = 0;
for (let i = min; i <= max; i++) {
// Count divisors
if (multiple % i === 0) {
divisorCount += 1;
}
}
if (divisorCount === numberDivisors) {
return multiple;
}
}
}
smallestCommons([1, 5]);