Write a JavaScript Program to Print All Prime Numbers in an Interval

In this article, we will discuss how to write a JavaScript program that prints all prime numbers within a given interval.

Prime numbers are those numbers that are only divisible by 1 and itself. For example, 2, 3, 5, 7, 11, 13, and so on are prime numbers.

To print all the prime numbers in an interval, we need to iterate over all the numbers in that interval and check if each number is prime or not.

We can check if a number is prime by dividing it by all the numbers from 2 to the square root of that number.

If the number is divisible by any of these numbers, then it is not a prime number.

Let’s write the code for this program.

function printPrimesInInterval(start, end) {
  for (let i = start; i <= end; i++) {
    let isPrime = true;
    
    for (let j = 2; j <= Math.sqrt(i); j++) {
      if (i %% j === 0) {
        isPrime = false;
        break;
      }
    }
    
    if (isPrime && i !== 1) {
      console.log(i);
    }
  }
}

In this code, we have defined a function printPrimesInInterval that takes two arguments start and end, which are the start and end points of the interval. We have used a nested loop to iterate over all the numbers in this interval.

The inner loop starts from 2 and goes up to the square root of the current number, checking if it is divisible by any of these numbers. If it is, then the isPrime variable is set to false and the loop is broken.

After the inner loop, we check if the current number is prime and not equal to 1. If it is, then we print it to the console.

Let’s test our program by calling this function with different intervals.

printPrimesInInterval(1, 20);

Output:

2
3
5
7
11
13
17
19

This program will print all the prime numbers between 1 and 20, which are 2, 3, 5, 7, 11, 13, 17, and 19.

In conclusion, we have learned how to write a JavaScript program to print all prime numbers in an interval.

This program can be useful in various mathematical and programming problems where we need to work with prime numbers.