问题
Input: 13195
Expected Result: 29 (largest prime factor of input)
Actual Result: 2639 (largest factor of input, but not a prime number)
I didn't bother with even numbers because the largest prime will either be 2 or some odd prime multiplied by 2 to get the input, so what's the point.
function findPrimeFactor(num) {
let prime;
for (let factor = 3; factor < num; factor += 2) {
if (num % factor === 0) {
for (let i = 3; i < factor; i += 2) {
if (factor % i === 0) {
break;
}
else {
prime = factor;
}
}
}
}
return prime;
}
回答1:
The problem of your code is in the else block. Where every time the program flow enters that block, you replace the prime
value with factor
value. The answer is to adding an extra temporary variable and in the else block, replacing the value of that.
I did it for you in below code:
function findPrimeFactor(num) {
let prime;
let temp = 3; // Default value for numbers those their largest prime factor is 3
for (let factor = 3; factor < num; factor += 2) {
if (num % factor === 0) {
for (let i = 3; i < factor; i += 2) {
if (factor % i === 0) {
temp = prime; // This value is not prime, so we should not replace the value of prime variable with it.
break;
}
else {
temp = factor; // This factor could be prime. We save it in the temp. If the for loop never meets the upper if block, so this is prime and we can have it.
}
}
prime = temp; // temp value now is a prime number. so we save it to prime variable
}
}
return prime;
}
I just corrected your code behavior and don't add extra behavior to it. Hope this helped you.
回答2:
for reference click here, there was other languages, I done the js one
function findPrimeFactor(num) {
// Initialize the maximum prime factor
// variable with the lowest one
let prime = -1;
// Print the number of 2s
// that divide n
while (num % 2 === 0) {
prime = 2;
num = num / 2;
}
// n must be odd at this point,
// thus skip the even numbers
// and iterate only for odd
// integers
for (let factor = 3; factor <= Math.sqrt(num); factor += 2) {
while (num % factor === 0) {
prime = factor;
num = num / factor;
}
}
// This condition is to handle
// the case when n is a prime
// number greater than 2
if (num>2)
prime = num;
return prime;
}
来源:https://stackoverflow.com/questions/50970495/javascript-function-not-returning-largest-prime-factor