I’m doing the Smallest Common Multiple problem. I’ve tried different logics, but nothing worked. I ended up creating one huge array of numbers to compare against the given array. The performance seems to be abysmal, but I’m wondering if this can be considered valid.
function smallestCommons(arr) {
let hugeNumber = 6056821;
let hugeArray = [];
let newArr = [];
let start = Math.min(...arr) // in case arr isn't sorted, populate newArr starting from lowest number using the first loop
let end = Math.max(...arr)
arr = newArr // now arr is [18, 19, 20, 21, 22, 23]
for (let i = start; i <= end; i++) {
newArr.push(i)
}
for (let i = 1; i <= hugeNumber; i++) { // populate hugeArray
hugeArray.push(i)
}
for (let n of hugeArray) { // retrieve the number from hugeArray that is true for all numbers in arr
if (arr.every((a) => n % a === 0)) {
return n;
}
}
}
console.log(smallestCommons([23, 18]))```
In code, if it gives you the right answer, I wouldn’t call it cheating.
Is it good practice though… egh… no… for a few reasons.
First, memory. As you said, it’s a HUGE array. That’s a lot of memory being used up to store some numbers… that are in order anyway. Why not just loop from 0 to hugeNumber and check each one?
Second, speed. Just some quick logic, if one of the numbers in arr is 5, than only every fifth number could possibly by the lowest common multiple. So why check every single number?
Third, reliability. What happens if the array I give you contains hugeNumber + 1?
I guess I could remove it, but I’m not sure how. Can I get a hint? xD
EDIT: just figured it out, looks a bit better now
function smallestCommons(arr) {
let hugeNumber = 100000000000;
let newArr = [];
let start = Math.min(...arr); // in case arr isn't sorted, populate newArr starting from lowest number using the first loop
let end = Math.max(...arr);
arr = newArr // now arr is [18, 19, 20, 21, 22, 23]
for (let i = start; i <= end; i++) {
newArr.push(i)
}
for (let i = 1; i <= hugeNumber; i++) { // loop through hugeNumber until the value is found
if (arr.every((a) => i % a === 0)) {
return i;
}
}
}
Bit of a tricky question for you - what is the absolute smallest number that might work as a multiple of all numbers from start to stop. Think super small examples here. What if the range is [1, 2]?
Well, that’s beyond my comprehension right now
Thank you for your help. And setting hugeNumber to Infinity is also a fix, right? That way all numbers are covered.