Given a positive number n > 1 find the prime factor decomposition of n. The result will be a string with the following form :
"(p1**n1)(p2**n2)...(pk**nk)"
where a ** b
means a
to the power of b
with the p(i) in increasing order and n(i) empty if n(i) is 1.
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"
学习总结:分解质因数、while、for循环使用
javascript版本
1.自己
function primeFactors(n){
//your code here
let res = "";
let count;
for(let i = 2 ; i <= n ; i++){
count = 0;
while(n%i === 0){
count++;
n = n/i;
}
if(count > 1){
res += `(${i}**${count})`;
}else if(count === 1){
res += `(${i})`;
}
}
return res;
}
2.他人
function primeFactors(n){
for (var i=2, res="", f; i <= n; i++) {
f=0;
while (n%i == 0) { f++; n/=i }
res += f ? "(" + ( f>1 ? i+"**"+f : i ) +")" : ""
}
return res || "("+n+")"
}
3.他人
function primeFactors(n){
for(var s = '', d = 2;n>1;d++) {
for (var k = 0;n%d == 0;k++, n/=d);
s += k ? (k==1 ? `(${d})` : `(${d}**${k})`) : '';
}
return s
}