Hello guys, here is my solution to this problem.
It is working as intended, but i have a question about optimization.
In this piece of code
let res = Math.max(…arr) * 10;
Instead of starting from 1 and loop everything until variable res is divisible by all numbers in the array i started this number from math.max(…arr) * 2 and everything worked.
To make it faster i then started changing the multiplication so it starts at the highest number we can while everything still working.
Past Math.max(…arr) * 10 for example Math.max(…arr) * 11 it wont work and i understand why, but i want to understand how could i find this out this starting value without trial and error, im sure there is some mathematical formula here which I would want to understand it.
Thanks in advance.
Your code so far
function smallestCommons(arr) {
// complete the array with all numbers between the numbers in the paramenters
for (let i = Math.min(...arr) + 1; i < Math.max(...arr); i++) {
arr.push(i);
}
// Assign a starting value to start the loop
let res = Math.max(...arr) * 10;
//Check if all numbers in the array are divisible by result
let isDivisible = () => arr.every(n => res % n === 0);
// Increment result in case all numbers in the array are not divisable by result
do {
res++;
} while(isDivisible() !== true)
return res;
}
smallestCommons([10,2]);
Link to the challenge: