Javascript program to print all prime numbers in an Interval

This is a preview lesson
Register or sign in to take this lesson.

Introduction

In this article, we will explain how to print prime numbers in an interval using Javascript.

Here we will write a program which will prints the prime number between 1 and 100.

A prime number is a number that can only be divided by itself and by 1. Examples include 2, 3, 5, 7,9,11,13 etc. 

Example


console.log('Prime numbers between 1 and 100 are:');

//Sets up the counter 1-100
for (var counter = 1; counter <= 100; counter++) {
   //Sets each counter value to false automatically 
    var notPrime = false;
    for (var i = 2; i <= counter; i++) {
      //Check whether counter is a prime number
        if (counter%i===0 && i!==counter) {
            notPrime = true;
        }
    }
   //print counter if it is prime number
    if (notPrime === false) {
        console.log(counter);
    }
}

Here we have added for loop with counter variable with intial value 1 to 100.We have set variable notPrime with auto set false value. Then We have created a for loop using a variable called i. The loop increases by one each time until it reaches one less than the counter. After that we have checked whether the current number is prime number or not.
If the current number is divided by the i number and the result is 0, then it is not a prime number, and the notPrime flag is set to true. If notPrime is false, the console will print the number.

Output

"Prime numbers between 1 and 100 are:"
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