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.

Javascript




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.



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:

  • Iterate through all numbers from 2 to N (since 1 is not a prime number).
  • For each number, check if it is divisible by any number other than 1 and itself.
  • If a number is only divisible by 1 and itself, it is a prime number.

Similar Reads

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....

Print Prime Numbers from 1 to N using Array Methods

...