/* 对于给定的N, 使factor = 2, 3, 4, 5, 6...,
如果递增至某个factor时, 当其能被N整除时, 则(N/factor)是N的最大因数。
其中属于(N/factor)的因数也必然是N的因数。
如果此时(N/factor)恰巧是质数,则返回其值,程序结束;
如果此时(N/factor)不是质数,则求它的最大质因数即为N的最大质因数;
重复上述过程即可最终求解。 */
function myMaxPrimeFactors(num) {
if(num <= 0) {
console.log('Plese input a positive integer!');
return;
}
var factor = 2;
var lastFactor = 1;
while(num > 1) {
if(num % factor == 0) {
lastFactor = factor;
num = num / factor;
} else {
factor = factor + 1;
}
}
return lastFactor;
}
console.log(myMaxPrimeFactors(600851475143));
console.log(myMaxPrimeFactors(2*3*5*7*11*13));
console.log(myMaxPrimeFactors(20));
console.log(myMaxPrimeFactors(2));
console.log(myMaxPrimeFactors(1));
console.log(myMaxPrimeFactors(0));
console.log(myMaxPrimeFactors(-10));
运行结果:
6857
13
5
2
1
Plese input a positive integer!
Plese input a positive integer!