Eratosthenes sieve in JavaScript

<<algorithm

 

prime

<!DOCTYPE html>
<html>
<body>
<script>

var n = prompt("n:", "");
var deleted = [], i, j;
if (n < 2) alert("No prime numbers in the given range");
else{
  for(i = 2; i <= n; i++) deleted[i] = false;
  i = 2;
  do{
    if (!deleted[i]){
      j = i * i;
      while(j <= n){
        deleted[j] = true;
        j += i;
      }
    }
    i++;
  } while ((i * i) <= n);
  for(i = 2; i <= n; i++) if (!deleted[i]) document.write(i+" ");
}

</script> 
</body>
</html>
 

Line Number

Algorithm Step (Flowchart)

Description of Program Line

-

1

START of the program (HTML/script initialization).

6

2

Reading the value of n using the prompt() function (Read: n).

7

-

Declaration of the deleted array and variables i and j.

8

3, 4

Checking the initial condition (n < 2) and displaying the error message (alert()).

9

-

Start of the else block (for n >= 2).

10

6

Initialization of the deleted array (marking all numbers from 2 to n as potentially prime (false)).

11

5

Setting the iterator i to 2 (i := 2).

12

-

Start of the main do...while loop.

13

9

Condition checking if i has not been deleted (!deleted[i]), i.e., if it is a prime number.

14

8

Initialization of the multiple iterator j to the square of i (j := i \cdot i).

15

11

Inner while loop condition checking if j does not exceed n (j \le n).

16

10

Marking the multiple j as composite (deleted[j] = true).

17

12

Moving to the next multiple of i (j := j + i).

-

-

Implicit loop iteration (return to step 11's check).

20

13

Incrementing i to the next candidate number (i := i + 1).

21

7, 14

The main loop's termination condition (while ((i * i) <= n)).

22

15, 16, 17, 18

Output Loop (for loop) combining initialization (15), check (16), writing the number (17), and increment (18).

-

19, 20

STOP of the program (loop termination and script end).