hey, everyone
I just have solved the Smallest Common Multiple from Intermediate Algorithm Scripting
I consider my solution as not the most rational solution
here is is:
function completeArray(arr){
//here's completeArray function, nothing complicated
var max,min;
if(arr[0]>arr[1]){
max=arr[0];
min=arr[1];
}else{
max=arr[1];
min=arr[0];
}
var newArr=[];
for(var i=min;i<=max;i++)
newArr.push(i);
return newArr;
}
function primeFactors(num){
//nothing difficult here as well
var primeArr=[];
if(num===1)
primeArr.push(1);
while(num%2===0){
primeArr.push(2);
num=num/2;
}
var upperbound=Math.floor(Math.sqrt(num));
for(var i=3;i<=upperbound;i+=2)
while(num%i===0){
primeArr.push(i);
num=num/i;
}
if(num>2)
primeArr.push(num);
return primeArr;
}
function findSet(arr){
return arr.reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
}
function SCMOfTwoNums(arr1,arr2){
//it's easier to explain by examples:
//for instance primeFactors functionn passed her to arrays
//for number 315 it's [3,3,5,7] and for 456 it's [2,2,2,3,19]
//then findSet function is used
//it returns set which contains properties (-prime factors) and values (-how much this prime factor is repeated in the array)
//thus for my example here're two sets: {3:2,5:1,7:1} and {2:3,3:1,19:1}
var set1 = findSet(arr1);
var set2 = findSet(arr2);
var arr=[];
//then by few for loops and conditional statements function creates array
for(var prop in set1){
if(set1[prop]>=set2[prop] || !(set2.hasOwnProperty(prop))){
for(var i=0;i<set1[prop];i++)
arr.push(prop);
}else if(set2[prop]>set1[prop]){
for(var j=0;j<set2[prop];j++)
arr.push(prop);
}
}
for(var prop2 in set2){
if(!(set1.hasOwnProperty(prop2))){
for(var k=0;k<set2[prop2];k++)
arr.push(prop2);
}
}
//multiplication of all elements in this array gives us desired result
var mult=1;
for(var t=0;t<arr.length;t++){
mult*=parseInt(arr[t]);
}
return mult;
}
function smallestCommons(arr) {
//create a array of numbers which are between two given
//so, for example, given arr=[3,8] then newArray=[3,4,5,6,7,8]
var newArray=completeArray(arr);
//so now, SCMOfTwoNums is much more interesting function
//within primeFactors function it finds the Smallest Common Multiple of two numbers
//Firstly, the primeFactors function finds all prime factors of the given number
//and it returns the array of them
//given 315, primeFactors will return [3,3,5,7]
//Secondly, SCMOfTwoNums takes those arrays and returns SCM
var mult=SCMOfTwoNums(primeFactors(newArray[0]),primeFactors(newArray[1]));
//within for loop I can find SCM that suits for every number between arr[0] and arr[1]
for(var i=2;i<newArray.length;i++){
mult=SCMOfTwoNums(primeFactors(mult),primeFactors(newArray[i]));
}
return mult;
}
smallestCommons([3,7]);
I wrote some comments, so it gonna be easier to understand
I hope to see your feedback about it and your solutions as well! thanks