https://www.codewars.com/kata/53c93982689f84e321000d62/javascript
My answer / AC
var isPrime = num => {
for(let i=2; i*i<=num; i++){
if(num%i == 0) return false;
}
return num>1;
};
function getAllPrimeFactors(n) {
if(!n || n<0 || n%1!==0) return [];
if(n==1) return [1];
var rest = n;
var res = [];
for(let i=2; i<=n; i++){
while(isPrime(i) && rest%i == 0) {
res.push(i);
rest /= i;
}
}
return res;
}
function getUniquePrimeFactorsWithCount(n) {
if(!n || n<0 || n%1!==0) return [[],[]];
var mapping = {};
var arr = getAllPrimeFactors(n);
arr.forEach((o)=>{
if(mapping[o]) {
mapping[o] += 1;
} else {
mapping[o] = 1;
}
});
return [Object.keys(mapping).map(e=>Number(e)), Object.values(mapping)];
}
function getUniquePrimeFactorsWithProducts(n) {
var arr = getUniquePrimeFactorsWithCount(n);
var res = [];
for(let i=0; i<arr[0].length; i++){
res.push(Math.pow(arr[0][i],arr[1][i]));
}
return res;
}
Best answer
var primeFactors
var primeWithCount
var primeWithProduct
function getAllPrimeFactors(n) { getPrime(n); return primeFactors }
function getUniquePrimeFactorsWithCount(n) { getPrime(n); return primeWithCount}
function getUniquePrimeFactorsWithProducts(n) { getPrime(n); return primeWithProduct}
function getPrime(n){
primeFactors= (n==1)? [1] : []
primeWithCount=(n==1)? [[1],[1]] : [[],[]]
primeWithProduct=(n==1)? [1] : []
for(var i=2; i<=n ; i++){
for (pow=0; n%i == 0; pow++){
n=n/i
primeFactors.push(i)
}
if (pow!= 0) {
primeWithCount[0].push(i);
primeWithCount[1].push(pow)
primeWithProduct.push(Math.pow(i,pow))
}
}
}
好在哪里?
- 一步到位,只要执行一个流程,三个答案都有了。
Recap
- 活学活用,刚学会的判定质数方法isPrime()
- 多思考有没有更简洁的办法,学会从for循环的判断条件不一定为
i<n
开始,还能是n%i == 0
网友评论