JavaScript:函数未返回最大素数

时间:2018-06-21 14:03:14

标签: javascript loops primes prime-factoring

输入: 13195
预期结果: 29 (输入的最大素数)
实际结果: 2639 (最大的输入因子,但不是素数)

我不会打扰偶数,因为最大质数将是2或一些奇数质数乘以2以得到输入,所以有什么用。

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;
}

2 个答案:

答案 0 :(得分:0)

供参考click here,还有其他语言,我做了js语言

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;
}

答案 1 :(得分:0)

您的代码问题在else块中。程序流每次进入该块的位置,都用prime值替换factor值。答案是添加一个额外的临时变量,然后在else块中替换其值。 我在下面的代码中为您做到了:

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;
}

我只是纠正了您的代码行为,并且没有在代码中添加额外的行为。 希望这对您有所帮助。