Tell us what’s happening:
I am trying to find the smallest common multiple using the formula:
smallestCommonMultiple = greatestCommonMultiple / largestCommonDivisor
I’ve found greatestCommonMultipler and want to use Euclid’s algorithm for finding the largest common divisor, but when I peek, the solution codes are so short and seem to be using only one formula, where I use two. (I peeked, didn’t read)
I can’t find another formula. Is it because I’m using recursion to find gcm, then using recursion to find gcd, and dividing at the end, when I should really be using recursion to find gcm/gcd each time? (hard to put in words…)
Your code so far
function smallestCommons(arr) {
let x = arr[0];
let y = arr[1];
let array = createArrayFrom(x,y);
console.log(array);
let gcm = greatestCommonMultiple(array);
console.log(gcm);
let gcd = greatestCommonDivisor(array);
console.log(gcd);
let scm = gcm / gcd;
console.log("scm " + scm);
return scm;
}
function createArrayFrom(x,y) {
let array = [];
if (y-x>0) {
for (let i=y; i>x-1; i--) {array.push(i)}
}
if (x-y>0) {
for (let i=x; i>y-1; i--) { array.push(i)}
}
return array;
}
function greatestCommonMultiple(array) {
let product = firstProduct(array);
let index = 2;
return checkNumbersRecursively(product, array, index);
}
function firstProduct(array) {
return array[0] * array[1];
}
function checkNumbersRecursively (product, array, index) {
console.log(index, product)
if (index == array.length) {
return product;
}
if (product % array[index] != 0) {
product *= array[index];
}
return checkNumbersRecursively(product, array, index+1);
}
function greatestCommonDivisor(array) {
}
smallestCommons([2,10]);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15
.
Challenge: Smallest Common Multiple
Link to the challenge: