Skip to content

Instantly share code, notes, and snippets.

@smiller171
Last active December 11, 2016 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smiller171/cff262522f34875a25340f3713f89f24 to your computer and use it in GitHub Desktop.
Save smiller171/cff262522f34875a25340f3713f89f24 to your computer and use it in GitHub Desktop.
find least common multiple of all numbers in a range.
function smallestCommons(arr) {
arr.sort(function(a,b) {
return b-a;
});
var min = arr[1];
var max = arr[0];
var allPrimeFactors = [];
var availablePrimes = [];
var reducedFactors = [];
var poweredFactors = [];
var result = 0;
for(var i=min; i<=max; i++) {
allPrimeFactors.push(getPrimeFactors(i));
}
availablePrimes = allPrimeFactors.reduce(function(prev,curr) {
for (var i=0; i<curr.length;i++) {
if (prev.indexOf(curr[i]) === -1) {
prev.push(curr[i]);
}
}
return prev;
}, [])
for(var i=0; i<availablePrimes.length; i++) {
var currentPrime = availablePrimes[i];
var finalCount = 0;
for (var i1=0; i1<allPrimeFactors.length; i1++) {
var currentFactors = allPrimeFactors[i1];
var currentCount = 0;
if (currentFactors.indexOf(currentPrime) > -1) {
for(var i2=0; i2<currentFactors.length; i2++) {
if (currentFactors[i2] === currentPrime) {
currentCount += 1;
}
}
}
if(currentCount > finalCount) {
finalCount = currentCount;
}
}
poweredFactors.push(Math.pow(currentPrime,finalCount));
}
result = poweredFactors.reduce(function(prev,curr) {
return prev*curr;
})
return result;
}
function getPrimeFactors(num) {
var primes = findPrimes(num);
var remainder = num;
var results = [];
while(primes.indexOf(remainder) === -1 && remainder > 1) {
for(var i=0; i<primes.length && remainder > 1; i++) {
var prime = primes[i];
while(remainder % prime === 0) {
results.push(prime);
remainder /= prime;
}
}
}
if (remainder > 1) {
results.push(remainder);
}
return results;
}
function findPrimes(max) {
var possibles = [];
var i = 0;
for (i=2; i<=max; i++) {
possibles.push(i);
}
for(i=0;i<possibles.length;i++) {
var current = possibles[i];
var product = 0;
for(var i1=current; product<=max; i1++) {
product = current*i1;
var index = possibles.indexOf(product);
if (index > -1) {
possibles.splice(index, 1);
}
}
}
return possibles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment