Open In App

JavaScript Program to Display Prime Numbers Between Two Intervals Using Functions

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Prime numbers are natural numbers greater than 1 that are only divisible by 1 and themselves. In this article, we will explore how to create a JavaScript program to display all prime numbers between two given intervals using functions.

Approach 1: Using Basic Loop and Function

The most straightforward approach is to use a loop to iterate through each number in the given interval and check if it is a prime number using a separate function. In this example, we have a function isPrime that checks if a number is prime, and a function displayPrimes that uses isPrime to display all prime numbers in a given range.

Javascript




function isPrime(number) {
    if (number <= 1) return false;
    for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) return false;
    }
    return true;
}
 
function displayPrimes(start, end) {
    for (let i = start; i <= end; i++) {
        if (isPrime(i)) {
            console.log(i);
        }
    }
}
 
// Driver code
let num1 = 500;
let num2 = 600;
 
displayPrimes(num1, num2);


Output

503
509
521
523
541
547
557
563
569
571
577
587
593
599

Approach 2: Using Array Methods

We can also use JavaScript array methods to make the code more concise and functional. In this approach, we use the Array.from method to create an array of numbers in the given range, the filter method to keep only the prime numbers, and the forEach method to log them.

Javascript




function isPrime(number) {
    return number > 1 && Array.from(
        { length: Math.sqrt(number) },
        (_, i) => i + 2)
        .every(divisor => number % divisor !== 0);
}
 
function displayPrimes(start, end) {
    Array.from({ length: end - start + 1 }, (_, i) => i + start)
        .filter(isPrime)
        .forEach(prime => console.log(prime));
}
 
// Driver code
let num1 = 500;
let num2 = 600;
 
displayPrimes(num1, num2);


Output

503
509
521
523
541
547
557
563
569
571
577
587
593
599



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads