Hey guys,
I’ve been stuck on this problem for a few days now and i’ve totally redone my indent preformatted text by 4 spacescode for it once. My algorithm can find the lcm of 2 numbers and check if the numbers in between the input numbers can divide evenly into the lcm, but I don’t know how to find the next lowest lcm if the actual lcm isn’t divisible by the middle numbers.
Any ideas on how to do this with the code that I have?
Thanks
// Main problem: How do I find the next common multiple if the LCM isn't divisible by all nums inbetween???
function gcd(a, b){ // a and b are integers
if(b === 0 || a === b)
return a;
else if(a > b)
return gcd(a-b,b);
else if(b > a)
return gcd(a,b-a);
}
//Test
//console.log(gcd(54,24)); //returns 6
function lcm(a,b){ // a and b are integers
var lcm = (a*b)/gcd(a,b);
/*
for(var i = 0; i < arr.length; i++){
lcm = (lcm * arr[i]) / gcd(lcm, arr[i]);
}*/
return lcm;
}
// Test... does work when nums are flipped ie. [1,5] is same as [5,1]
//console.log(lcm(8,6)); //returns 24
function numsBetween(arr){ // Returns an array of the the nums between and including the 2 elements in the input array
var num1 = arr[0],
num2 = arr[1],
btwn = [];
for(var i=num1; i<=num2; i++)
btwn.push(i);
return btwn;
}
// Test
//console.log(numsBetween([1,5])); //will return [1,2,3,4,5]
function areBtwnsMultiples(lcm, btwns){ //Checks to see if nums in between are multiples of the lcm. 'btwns' is an array of nums
var mults = true;
btwns.forEach(function(num){ //For each num in btwns, if the proposed lcm isn't evenly divisible, then not all nums are multiples of the proposed lcm
if(lcm % num !== 0)
mults = false;
});
return mults; //Return true if all nums divide evenly into the proposed lcm
}
// Test
//console.log(areBtwnsMultiples(60,[1,2,3,4,5])); //will return 'true'
function smallestCommons(arr) {
//1) get gcd using formula (done inside lcm function)
//2) get lcm using gcd and lcm formula
var lcm = lcm(arr[0], arr[1]);
//3) make sure all in between numbers also divide into the lcm
if(!areBtwnsMultiples(lcm, numsBetween(arr)))
// Find the next lcm... but how???
//4) return the lcm
return lcm;
}
//var ans = smallestCommons([1, 5]); //should return 60.
//var ans = smallestCommons([5, 1]); //should return 60.
//var ans = smallestCommons([1, 13]); //should return 360360.
//var ans = smallestCommons([23, 18]); //should return 6056820.
console.log(ans);