M
M
Monserator2021-06-15 17:12:24
JavaScript
Monserator, 2021-06-15 17:12:24

Is there a bug in the function?

Given a function to check prime numbers, using it you need to find all prime numbers from 1 to 100. Here is the solution

<br>
    function isPrime(num) {<br>
        for (let i = 2; i < num; i++) {<br>
            if (num % i == 0) {<br>
                return false;<br>
            }<br>
        }<br>
        <br>
        return true;<br>
    }<br>
    let arrPrime = [];<br>
<br>
    for (let i = 1; i <= 100; i++){<br>
        if (isPrime(i)){<br>
            arrPrime.push(i);<br>
        }<br>
    }<br>
<br>
    console.log(arrPrime);<br>


and outputs to the console
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97]


Although when checking console.log(2 % 2 == 0); returns true, i.e. should return false and push should not work, although I understand that 2 is a prime number ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-06-15
@Monserator

It doesn’t get to the check because the cycle doesn’t start at all, because the condition i < num is not met .
But your outer loop should start not from 1, but from 2, because 1 is by definition not a prime number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question