Algorithim help!

Tell us what’s happening:
this is the answer i got by googling how to get the smallest common mulitple
i basically copied it thinking i understood it but it doesnt make no sense to me please can someone point me to some material thast can help me understand this sort of algorithm

Your code so far


function smallestCommons(arr) {
let max = Math.max(arr[0], arr[1]);
let min = Math.min(arr[0], arr[1]);
let range = [];

for (let i = min; i <= max; i++){
  range.push(i);
}
// i understand up to here!

let a = range[0];
for (let i = 1; i < range.length; i++){
  let b = range[i];
  let c = a;

  while ( a && b){
    if (a > b){ 
      a %= b;
    }else{
      b %= a;
    }
  }
  a = c * range[i] / (a+b);

}
return a
}
// this ^^^^^ confuses me big time!!!!!!!!!

console.log(smallestCommons([1,3]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36.

Challenge: Smallest Common Multiple

Link to the challenge:

Hi!

The code inside of the while loop uses the Euclidean algorithm to find the greatest common divisor (GCD) of a and b. Basically, the numbers a and b are repeatedly transformed with the remainder operation, a % b or b % a, until either a or b is 0 (or when a && b is false).

For example, if a = 6 and b = 4, the while loop would do the following:

a = 6, b = 4:
  a > b, so a = 6 % 4, or a = 2.

a = 2, b = 4:
  b > a, so b = 4 % 2, or b = 0.

a = 2, b = 0:
  Stop here since b = 0. The GCD is given by a + b, or 2.

Read Wikipedia’s description of the Euclidean algorithm or search for “Euclidean algorithm” if you’d like to learn more about this algorithm.

Once the GCD is found, the smallest/least common multiple is the product of the original two numbers divided by the GCD. For our example above, the least common multiple of 6 and 4 would be

6 * 4 / 2 = 24 / 2 = 12.

Maybe Wikipedia’s article on the least common multiple could provide some helpful context.

thank you for your reply and detail it helps me understand the thought process of programming more :slight_smile: now got to keep on being consistent and hopes it gels. thank you again!

1 Like