0

I am having trouble finding the problem with my short program, meant to find all the prime numbers between 2 and 100. I have tried rewriting the program several times; but my browser always slows to a halt when I try to run it. Any help would be much appreciated!

        function is_prime(x)
        {
            for (i = 2; i <= x / 2; ++i)
                if (x % i == 0) return false;
            return true;
        }

        for (i = 2; i < 100; ++i)
            if (is_prime(i)) console.log(i);
  • 1
    Always use curly brackets around the contents of `for` loops and `if` blocks, or at least until you know what the rules are. – Heretic Monkey Sep 14 '20 at 17:37
  • I suggest looking up more efficient prime number algorithms like the sieve of Eratosthenes which is much faster. – VLAZ Sep 14 '20 at 17:38
  • Read about [declaring variables in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types#Declaring_variables). Hint: in your code the same variable `i` is used inside the function and outside it, in the global code. – axiac Sep 14 '20 at 17:39
  • Does this answer your question? [How to find prime numbers between 0 - 100?](https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100) – Heretic Monkey Sep 14 '20 at 17:42

1 Answers1

1

The i in your loops are not declared

 function is_prime(x)
        {
            for (let i = 2; i <= x / 2; ++i)
                if (x % i == 0) return false;
            return true;
        }

for (let i = 2; i < 100; ++i)
    if (is_prime(i)) console.log(i);
Ahmed Gaafer
  • 1,603
  • 9
  • 26