Hi Campers!
I got completely stuck on Smallest Common Multiple challenge.
Can you give my any tips to get started?
Thank you,
Kuba
Hi Campers!
I got completely stuck on Smallest Common Multiple challenge.
Can you give my any tips to get started?
Thank you,
Kuba
I think I just don’t understand the algorithm. Translating it later into Javascript shouldn’t be the problem.
Here’s what I created as you suggested - Smallest common multiple for two numbers.
But how to make it working for array of numbers
function LCMforTwo(a,b){
var lcm = Math.abs(a * b) / gcd(a,b);
function gcd(a,b){
while (b != 0){
c = a % b;
a = b;
b = c;
}
return a;
}
return lcm;
console.log(lcm);
}
LCMforTwo(6541,498);
Hooray! Thank you so much for help
This is my final code. Gosh, that was really hard.
function smallestCommons(arr){
var min = Math.min(arr[0],arr[1]);
var max = Math.max(arr[0],arr[1]);
var range = [];
for(var i = min; i <= max; i++){
range.push(i);
}
var lcm = range[0];
for(var j = 1; j < range.length; j++){
lcm = (lcm * range[j]) / gcd(lcm, range[j]);
}
return lcm;
function gcd(a,b){
while (b != 0){
c = a % b;
a = b;
b = c;
}
return a;
}
}
I am also stuck, and, before resorting to solving the problem using the solution that has been so generously offered here, I wanted to still share my code here and ask what is wrong (well, even if everything is, I would still like to ask for some help )
my solution was:
function smallestCommons(arr) {
var newArr = [];
arr.sort(function(a,b){
return a-b
});
for (var i=arr[0]; i<=arr[(arr.length-1)]; i++) {
newArr.push(i);
}
for (var counter=1; counter>newArr[(newArr.length-1)]; counter++){
for (var j=0; j<newArr.length; j++) {
if (counter%arr[j]!==0) break;
}
}
return counter;
}
what I am doing is:
I have a feeling when I have an if-break statement I am still doing everything right, but then I just have no idea what to do further. In the meanwhile I will try to use the standard solution with dividing the a*b by the greatest common divisor. Thank you in advance, any help is appreciated!