function checkRange(num, temp) {
for (var i = 1; i < num; i++) {
console.log(temp % i, i, temp);
if (temp % i != 0) {
return false;
}
}
return true;
}
function smallestCommons(arr) {
arr.sort((a, b) => {return a > b})
var two = [arr[1]];
var check = false;
while (check == false) {
two.push(two[two.length - 1] + arr[1])
if (checkRange(arr[1], two[two.length - 1]) == true) {
check = true;
return two[two.length - 1];
}
}
console.log(two);
// not sure what to do with this
return two[two.length - 1];
}
smallestCommons([1, 13]);
So I do realize that it's probably an infinite loop, but I would like to know why this is happening.
My code is not working for:
smallestCommons([1, 13]) should return 360360.
smallestCommons([23, 18]) should return 6056820.
The code works with the following steps:
Get lower number as first index (sort)
Make a loop that will keep adding the last index with arr[1] and validate if every number counting up to arr[0] can be divided evenly for the last element of the array.
This was my answer when I was learning:
function checkall(arr, lcm) {
let num1 = arr[0]
let num2 = arr[1]
// Get the start number
let first = (num1 < num2) ? num1 : num2;
// Get the end number
let last = (num1 > num2) ? num1 : num2;
while (first != last) {
// Check if lcm is divisble
if (lcm % first != 0) {
// If not then get an lcm of the number and existing lcm
lcm = getlcm(first, lcm)
}
// Increment first
first++
}
// Return the end lcm
return lcm
}
function smallestCommons(arr) {
// Get the two numbers
let num1 = arr[0]
let num2 = arr[1]
// Feed the array and lcm into the checkall function
return checkall(arr, getlcm(num1, num2))
}
function getlcm(num1, num2) {
// Get the minimum number out of both
let min = (num1 > num2) ? num1 : num2;
while (true) {
// Check if a number is divisible by both
if (min % num1 == 0 && min % num2 == 0) {
// If matches, this is the lcm
// Break the loop and return the lcm
return min
break;
}
// Increment the number
min++;
}
}
console.log(smallestCommons([1, 13]))
console.log(smallestCommons([23, 18]))
console.log(smallestCommons([2, 10]))