无法找出 Javascript 中无限循环的原因(从 Python 翻译一个函数后)

Cant' find out the cause of infinite loop in Javascript (After translating a function from Python)

我正在将我在 Python 中编写的函数翻译成 Javascript 但是在 JS 中我有一个无限循环,而在 Python 中一切正常。

这是我在 Python 中的代码:


def isPrime(n: int) -> bool:

    # Since neither 1 nor 0 is a prime number, return false
    if n == 1 or n == 0:
        return False

    # Loops from 2 to n
    for i in range(2, n):

        # If the number is divisible by i, then n is not a prime number
        if n % i == 0:
            return False

    # Otherwise, n is a prime number
    return True

def getPrimes(n: int) -> list[int]:
    """
    Take a positive int number n as a parameter and prints to the console the first n prime numbers
    """

    primes = []
    count = 0

    while len(primes) < n:
        if isPrime(count):
            primes.append(count)
        count += 1

    return primes

这是我在 Javascript 中的代码:


function isPrime(num) {

    // Since neither 1 nor 0 is a prime number, return false
    if (num == 1 || num == 0) {
        return false
    }

    // Loops from 2 to n
    for (let i = 2; i <= num; i++) {
        
        // If the number is divisible by i, then n is not a prime number
        if (num % i == 0) {
            return false
        }
    }

    // Otherwise, n is a prime number
    return true
}

function getPrimes(num) {

    let primes = [];
    count = 0;

    while (primes.length < num) {
        if (isPrime(count) === true) {
            primes.push(count);
        }
        count++;
    }

    return primes;
}

在 Python 中,当我调用函数 getPrimes(n) 时,它正确 returns 一个包含前 n 个素数的数组。

但在Javascript中,相同的函数会导致无限循环。

为什么会这样?提前谢谢你。

它不会导致无限循环,你的 isPrime(num) 函数只是 returns false 每个数字,因为你有 i <= num,这会导致 num % num == 0评估为 true 并返回 false。只需将其修复为 i < num

function isPrime(num) {

    // Since neither 1 nor 0 is a prime number, return false
    if (num === 1 || num === 0) {
        return false
    }

    // Loops from 2 to n
    for (let i = 2; i < num; i++) {
        
        // If the number is divisible by i, then n is not a prime number
        if (num % i === 0) {
            return false
        }
    }

    // Otherwise, n is a prime number
    return true
}

function getPrimes(num) {

    let primes = [];
    count = 0;

    while (primes.length < num) {
        if (isPrime(count) === true) {
            primes.push(count);
        }
        count++;
    }

    return primes;
}


console.log(getPrimes(10))  // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]