Hello!
I have been struggled with this challenge that I would rather see the solution and learn how others did.
Below solution mentioned that it is using “reduce()” for the block.
I tried to simulate loop from 1 to 5 but I cannot get how it works.
Could anybody explain to me??
What I don’t understand : What inside the for loop ; var GCD
Thank you in advance for your time and help!
Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Smallest Common Multiple :
function smallestCommons(arr) {
var range = [];
for (var i = Math.max(arr[0], arr[1]); i >= Math.min(arr[0], arr[1]); i--) {
range.push(i);
}
// can use reduce() in place of this block
var lcm = range[0];
for (i = 1; i < range.length; i++) {
var GCD = gcd(lcm, range[i]);
lcm = (lcm * range[i]) / GCD;
}
return lcm;
}
function gcd(x, y) {
// Implements the Euclidean Algorithm
if (y === 0)
return x;
else
return gcd(y, x%y);
}
}
// test here smallestCommons([1,5]);
Easiest way to figure out smallest common multiple is to figure out the greatest common divisor first (GCD).
So spoilers here; I am not very knowledgeable w/r/t maths, so had to look this up, but:
lowest common multiple of a and b (make it a function like lcm(a, b)) is equal to a times b divided by the greatest common divisor of a and b.
So this looks like (a * b) / gcd(a, b).
GCD is very easy to calculate:function gcd(a, b) {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}
(nb the [a, b] = [b, a] is an easy way to swap variables without using a temporary variable, I just used it to …