Tell us what’s happening:
Your code so far
function smallestCommons(arr) {
let smallNum = 0
let bigNum = 0
// Finds which number is larger in the array
if (arr[0] > arr[1]){
bigNum = arr[0]
smallNum = arr[1]
}
else{
bigNum = arr[1]
smallNum = arr[0]
}
//initializing counter + return value
let counter = 0
let finalNum = 0
//Goes to an arbitrary large number as the value to compare to provided values
for (let i=bigNum; i < 999999999; i++){
counter = 0
// Test each number on each provided value
for (let j=smallNum; j <= bigNum; j++){
//if it fits, counter + 1
if (j%i === 0){
counter++
// if counter = number of values between provided values, assigns return value
// to the number which is being compared
if (counter === bigNum - smallNum-1){
console.log("hi")
finalNum = i
break
}
}
}
}
console.log(finalNum)
return finalNum;
}
console.log(smallestCommons([5,1]));
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:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple
I tried to accomplish this problem using a nested for loop and a bunch of if statements, and while the execution gets almost all the way up the tree (tested this using console.log) it never activates the final if statement. I tried seeing if maybe I was supposed to do -1 or +1 for the value the counter needs to be at, however I could only get it to work with -3 with values of 1 and 5, meaning the counter isn’t going above 1. Could someone identify why the counter seems to stop working after it works the first time causing the if statement to never activate?