Open In App

JavaScript Program to Print Prime Numbers from 1 to N

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we’ll explore how to create a JavaScript program to print all prime numbers from 1 to a given number N.

To find prime numbers from 1 to N, we need to:



Print Prime Numbers from 1 to N using Basic Approach

Here’s a simple implementation to find and print prime numbers from 1 to N. The below code consists of two functions: isPrime and printPrimeNumbers.




function isPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return num > 1;
}
  
function printPrimeNumbers(n) {
    for (let i = 2; i <= n; i++) {
        if (isPrime(i)) {
            console.log(i);
        }
    }
}
  
printPrimeNumbers(100);

Output

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

Print Prime Numbers from 1 to N using Array Methods

You can also use JavaScript array methods to make the code more concise. This code defines two functions, printPrimeNumbers and isPrime, to print all prime numbers up to a given number n. The isPrime function checks if a number is prime, while printPrimeNumbers generates an array of numbers from 1 to n, filters out non-prime numbers, and prints the prime numbers.




function printPrimeNumbers(n) {
    Array.from({length: n}, (_, i) => i + 1)
         .filter(isPrime)
         .forEach(prime => console.log(prime));
}
  
function isPrime(num) {
    return num > 1 && Array.from(
        {length: Math.sqrt(num)}, (_, i) => i + 2)
        .every(divisor => num % divisor !== 0);
}
  
printPrimeNumbers(100);

Output
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

The Array.from() method is used to generate an array of numbers from 1 to N, filter() is used to keep only the prime numbers, and forEach() is used to print each prime number.


Article Tags :