JSFiddle - React, Tailwind, and code Playground
by torggya
JavaScript
/*Learned a lot. Could not figure this out at all, although I did make a for loop
that had minimal success. It worked, but it would take a very, very long time to complete
equations.
See https://jsfiddle.net/torggya/Lr8xfbk6/ for my failed version using for loops.
Check second possible solution here : https://jsfiddle.net/torggya/zLrdhh8z/
Looked up this on https://www.gorkahernandez.com/blog/fcc-bonfire-series-132-smallest-common-multiple/
Very informative. Recommended reading. Since this is not truly my own, I studied it and believe i Have come to understand it.
*/
function smallestCommons(arr) {//numbers are 5,1 in this example. First, get the range of numbers
var range = numberRange(arr);//between 5 and 1. Refer to numberRange(arr).
return range.reduce(function(a, b){//In here, reduce the range in the LCM and GCD functions.
return lcm(a,b); // LCM is Lowest Common Mulitple. GCD is Greatest Common Divisor. (a,b) returns 1,2; 2,3; 6,4; 12,5 concurrently.
//return lcm(a,b); returns 2, 6, 12, 60.
});
function lcm(a,b){ //Lowest Common multiple. This takes math.abs, which returns an absolute
return Math.abs(a * b) / gcd(a, b); //value, and divides it by the GCD function. returns
} //2, 6, 12, 60
//math.abs(a*b) returns 2, 6, 24, 60
//gcd(a, b) returns 1,1,2,1.
function gcd(a,b){ //GCD function. This is Euclid's algorithm.
var temp;//https://en.wikipedia.org/wiki/Euclidean_algorithm
while(b != 0){
temp = b;
b = a % b;
a = temp;
}
return a;
}
function numberRange(arr){//made this myself. Basically sorts the array from smallest to largest
var sorted = arr.sort(function(a, b) { // then makes an array with the whole range of numbers.
return a - b;
});
var numberList = [];
for (i = sorted[0]; i <= sorted[1]; i++){
numberList.push(i);
}
console.log(numberList);
return...