Smallest Common Multiple question

Smallest Common Multiple question
0

#1

Tell us what’s happening:
Why is the for loop on line 25 stopping prematurely?

Your code so far


function smallestCommons(arr) {
  var divArr = [];
  
  if (arr[0]>arr[1]) {
    arr = [arr[1], arr[0]];
    console.log("the numbers are " + arr);
  }
  function isItPrime(nr) {
     //console.log("running isItPrime for " + nr);
     if (nr==2) {
       //console.log(nr + " is prime");
          return true;
     } else {
     
      for (let j=2; j<nr; j++) {
        if (nr%j===0) {
         //console.log(nr + " is not prime");
          return false;
          }
        }
      // console.log(nr + " is prime");
          return true;
      }
    }
  for (let i=0; i<2; i++) {
    console.log("the number is " + arr[i]);
      for (let j=1 ; j<arr[i]; j++) {
        if (arr[i] % j == 0 && isItPrime(j)===true) {
          divArr.push(j);
        }
        
      }
      console.log("divArr is " + divArr);
    }
    console.log("divArr is now " + divArr);

}


smallestCommons([23,18]);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple


#2

What makes you think it is stopping prematurely?


#3

It doesn’t add all the prime divisors of the number in the loop


#4

I modified your last two for loops with some different console.log statements. See if this helps you figure out what is going on.

  console.log(divArr)
  for (let i = 0; i < 2; i++) {
    console.log(i)
    console.log("the number is " + arr[i]);
    for (let j = 1; j < arr[i]; j++) {
      console.log(j, arr[i])
      if (arr[i] % j == 0 && isItPrime(j) === true) {
        divArr.push(j);
        console.log(divArr)
      }

    }
    console.log();
  }
  console.log("divArr is now " + divArr);