JavaScript:函数未返回最大素数 [英] JavaScript: Function not returning largest prime factor
问题描述
输入: 13195
预期结果: 29 (输入的最大素数)
实际结果: 2639 (最大的输入因子,但不是素数)
Input: 13195
Expected Result: 29 (largest prime factor of input)
Actual Result: 2639 (largest factor of input, but not a prime number)
我没有打扰偶数,因为最大质数将是2或一些奇数质数乘以2来获得输入,所以有什么用.
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;
}
推荐答案
您的代码问题在else块中.程序流每次进入该块的位置,都用factor
值替换prime
值.答案是添加一个额外的临时变量,然后在else块中替换该变量的值.
我在下面的代码中为您做到了:
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.
这篇关于JavaScript:函数未返回最大素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!