Home > Software design >  Cant' find out the cause of infinite loop in Javascript (After translating a function from Pyth
Cant' find out the cause of infinite loop in Javascript (After translating a function from Pyth

Time:05-30

I'm translating a function I've wrote in Python to Javascript but In JS I have an infinite loop while in Python everything works fine.

Here's my code in 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

Here's my code in 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;
}

In Python, when I call the function getPrimes(n) it correctly returns an array containing the first n prime numbers.

But in Javascript, the same function causes an infinite loop.

Why is that happening? Thank you in advance.

CodePudding user response:

It's not causing infinite loop, your isPrime(num) function just returns false for every number, because you are having i <= num, which causes num % num == 0 evaluating to true and returning false. Just fix it to 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]
  • Related