Skip to content

Instantly share code, notes, and snippets.

@layonthebeech
Created September 27, 2016 14:13
Show Gist options
  • Save layonthebeech/aee0f0681c29265ddec4740b49b22a67 to your computer and use it in GitHub Desktop.
Save layonthebeech/aee0f0681c29265ddec4740b49b22a67 to your computer and use it in GitHub Desktop.
Description: You have to code a function getAllPrimeFactors which take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array. exemple: getAllPrimeFactors(100) returns [2,2,5,5] in this order. This deco…
function sieve(x) {
var arr = [];
var output = [];
for(var i = 0; i < x; i++) {
arr.push(true);
}
for(var i = 2; i <= Math.sqrt(x); i++) {
if(arr[i]) {
for(var j = i*i; j <x; j+=i) {
arr[j] = false;
}
}
}
for(var i =2; i < arr.length; i++) {
if(arr[i]) {
output.push(i);
}
}
return output;
}
function getAllPrimeFactors(n) {
var arr = [];
if(n <=0 || typeof n !== 'number' || n % 1 !==0) return arr;
if(n===1) return [1];
if(n===2) return [2];
var count = n;
var s = sieve(n);
for(var i = 0; i < s.length; i++) {
while(n % s[i] === 0) {
n = n/s[i];
arr.push(s[i]);
}
}
return arr;
}
function getUniquePrimeFactorsWithCount(n) {
var arr = getAllPrimeFactors(n);
var count = {};
var dup = [];
arr.forEach(function(i) {
count[i] = (count[i]||0)+1;
});
var t = [];
var x = [];
for(var c in count) {
t.push(parseInt(c))
x.push(count[c]);
}
dup.push(t)
dup.push(x)
return dup;
}
function getUniquePrimeFactorsWithProducts(n) {
var arr = getAllPrimeFactors(n);
var count = {};
var prod = [];
arr.forEach(function(i) {
count[i] = (count[i]||0)+1;
});
for(var c in count) {
prod.push(Math.pow(parseInt(c),count[c]))
}
return prod;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment