The Wayback Machine - https://web.archive.org/web/20241118012645/https://www.geeksforgeeks.org/javascript-program-to-print-prime-numbers-from-1-to-n/
Open In App

JavaScript Program to Print Prime Numbers from 1 to N

Last Updated : 19 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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.

  • isPrime(num) function: This function checks if a given number num is a prime number or not. It iterates from 2 to the square root of num (inclusive) and checks if num is divisible by any of these numbers. If it is, the function returns false, indicating that num is not a prime number. If num is not divisible by any number in the range, the function returns true, but only if num is greater than 1 (since 1 is not considered a prime number). This is an efficient way to check for primality, as it reduces the number of iterations needed.
  • printPrimeNumbers(n) function: This function prints all prime numbers up to a given number n. It iterates from 2 to n and uses the isPrime function to check if each number is prime. If a number is prime, it is printed to the console.
JavaScript
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.

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.


Similar Reads

JavaScript Program to Print All Prime Numbers in an Interval
In this article, we will explore a JavaScript program to find and print all prime numbers within a given range. A prime number is a natural number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23…, The program efficiently identifies and displays prime numbers within the specified range.
4 min read
JavaScript Program to Display Prime Numbers Between Two Intervals Using Functions
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 FunctionThe most straightforward approach is to use a loop to iterate through eac
2 min read
JavaScript Program to check Whether a Number can be Express as Sum of Two Prime Numbers
To check if a number can be expressed as the sum of two prime numbers, iterate through primes less than or equal to half of the given number. For each prime, check if the complementary prime exists by subtracting it from the target number and testing if the result is prime. If found, the number can be expressed as the sum of two primes. There are s
3 min read
Javascript Program for Prime Numbers
What are prime numbers?A prime number is a natural number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23... In other words, the prime number is a positive integer greater than 1 that has exactly two factors, 1 and the number itself.There are many prime numbers, such as 2, 3, 5, 7, 11,
5 min read
JavaScript Program to Print Pyramid Pattern by using Numbers
A pyramid pattern using numbers is a sequence of numbers arranged in a triangular shape, with each row displaying incrementing or decrementing numbers, creating a visually structured pattern. Example: 1 1 2 3 1 2 3 4 5 1 2 3 4 5 6 71 2 3 4 5 6 7 8 9ApproachWe initialize a variable n with the value 5. This variable determines the number of rows in t
5 min read
JavaScript Program to Print Even Numbers in a Linked List
A linked list is a data structure that stores the values at different memory locations concerning the next memory block of stored value. You can get all the even numbers stored in a linked list using the below methods. Table of Content Using While LoopUsing RecursionUsing While LoopTo print even numbers in a linked list using the while loop method,
2 min read
JavaScript Program to Print Positive Numbers in a Linked List
This JavaScript program aims to print positive numbers present in a linked list. A linked list is a data structure consisting of a sequence of elements, where each element points to the next element in the sequence. The program traverses the linked list and prints all the positive numbers encountered. Table of Content Iterative ApproachRecursive Ap
2 min read
JavaScript Program to Print Negative Numbers in a Linked List
This JavaScript program aims to print negative numbers present in a linked list. A linked list is a data structure consisting of a sequence of elements, where each element points to the next element in the sequence. The program traverses the linked list and prints all the negative numbers encountered. Table of Content Iterative ApproachRecursive Ap
2 min read
JavaScript Program to Print Odd Numbers in a Linked List
This article will show you different ways to find and print all the odd numbers in a linked list using JavaScript. Example: Input: 2->1->9->3 Output: 1, 9, 3 Input: 5->5->1->0->19->8 Output: 5, 5, 1, 19Table of Content Using Recursive ApproachUsing While LoopUsing For LoopUsing Recursive ApproachThis recursive method checks
4 min read
JavaScript Program to Print all Even Numbers in a Sorted Order of a Linked List
This JavaScript program is designed to identify all even numbers in a sorted order of a linked list. A linked list is a linear data structure where elements, known as nodes, are connected via pointers. The program iterates through the linked list to determine the all-even numbers in the sorted order it contains. There are several ways to print all
3 min read
JavaScript program to print even numbers in an array
Given an array of numbers and the task is to write a JavaScript program to print all even numbers in that array. We will use the following methods to find even numbers in an array: Table of Content Method 1: Using for Loop Method 2: Using while Loop Method 3: Using forEach LoopMethod 4: Using filter MethodMethod 5: Using for...of LoopMethod 6: Usin
5 min read
JavaScript Program to Print All Numbers Divisible by 3 and 5 of a Given Number
In this article, we are going to discuss how to print all the numbers that are divisible by 3 and 5. We will write a program for finding out those numbers. For this, we can use loop or conditional statements. Example: Input: 75Output: 0, 15, 30, 45, 60, 75Input: 150Output: 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150We can solve this by using the
4 min read
JavaScript Print shortest Path to Print a String on Screen
Given a screen with the English alphabet (A-Z) and a remote control with navigation keys (left, right, up, down), we have to determine the most efficient way to write a string using the remote. Starting from the top-left corner of the screen, we need to move through the alphabet to spell out the entire input string in the correct order. In this art
3 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
JavaScript Program to Check Prime Number By Creating a Function
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we will explore how to check if a given number is a prime number in JavaScript by creating a function. Table of Content Check Prime Number using for LoopCheck Prime Number using Array MethodsCheck Prime Number using RecursionChe
2 min read
JavaScript Program to Find Prime Factors
In this article, we will see all the methods to find the prime factors of a number using JavaScript. Methods to Find Prime Factors: Table of Content Using loops and Math.pow() MethodRecursive Approach with Spread OperatorSieve of Eratosthenes AlgorithmMethod 1: Using loops and Math.pow() MethodIn this method, we will use a JavaScript loop to iterat
3 min read
Print all Positive Numbers in a Range in JavaScript Array
To print all the possible numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the positive numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69]Range = [1 to 70]Output: 45, 63, all positive numbers lies inside the ran
3 min read
Print all Negative numbers in a Range in JavaScript Array
To print all the negative numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69]Range: [-1 to -70]Output: -22, -88, -69, all negative numbers lies inside
3 min read
Print all Positive Numbers in JavaScript Array
In JavaScript, arrays are the data structures used to store multiple elements. In some cases, we need to extract the elements that satisfy a specified condition. We can use a condition to extract all the positive numbers from an array with the below approaches. Example:Input: arr = [-1, -12, 35, -8, 45, 68, 99]Output: 35, 45, 68, 99 all positive nu
3 min read
Print all Even Numbers in a Range in JavaScript Array
We have to find all even numbers within a given range. To solve this question we are given the range(start, end) in which we have to find the answer. There are several ways to print all the even numbers in a range in an array using JavaScript which are as follows: Table of Content Using for Loop in JavaScriptUsing While Loop in JavaScriptUsing forE
3 min read
Print all Odd Numbers in a Range in JavaScript Array
Odd numbers are numbers that cannot be divided into equal parts. If we divide the odd number by 2, the remainder is 1. In JavaScript, if we want to print all Odd numbers in a range, we can print it by iterating over the array, applying the condition, and printing the odd numbers. There are various approaches to printing all odd numbers in a range i
4 min read
Print Strong Numbers Within a Range using JavaScript
In mathematics, a strong number is a number whose sum of the factorial of its digits is equal to the number itself. The task is to print all strong numbers within a given range in JavaScript. Example: 145 is a Strong number because: 1: 14: 4*3*2*1=245: 5*4*3*2*1=120120+24+1=145Since the sum is equal to number, 145 is a Strong number. Table of Conte
2 min read
Print Odd Numbers in a JavaScript Array
JavaScript provides us with various approaches for printing odd numbers in an array. The core concept behind finding an odd number is based on the fundamental arithmetic property that odd numbers leave a remainder of 1 when divided by 2. Table of Content Using JavaScript Filter() MethodUsing JavaScript ForEach() MethodUsing JavaScript For LoopUsing
4 min read
Print all Negative Numbers in JavaScript Array
In JavaScript, arrays are the data structures used to store the elements. In some cases, we need to extract the elements that satisfy the condition. To print all the negative numbers from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print
4 min read
Javascript Program to Print all possible rotations of a given Array
Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explanation: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotation arr[] = {3, 4, 1, 2} After third rotation arr[
3 min read
Javascript Program to Print array after it is right rotated K times
Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples :   Input: Array[] = {1, 3, 5, 7, 9}, K = 2. Output: 7 9 1 3 5 Explanation: After 1st rotation - {9, 1, 3, 5, 7} After 2nd rotation - {7, 9, 1, 3, 5} Input: Array[] = {1, 2, 3, 4, 5}, K = 4. Output: 2 3 4 5
2 min read
JavaScript Program to Print 1 to N using Recursion
In this article, we will see how to print 1 to N using Recursion in JavaScript. What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution to the bigger p
2 min read
JavaScript Program to Print N to 1 using Recursion
In this article, we will see how to print N to 1 using Recursion in JavaScript. What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution to the bigger p
1 min read
JavaScript Program to Print Pyramid Star Pattern
In this article, we will demonstrate how to create pyramid star patterns in JavaScript. The Possible Pyramid Star Patterns are:Upper pyramidInverted pyramidLeft inverted pyramidRight inverted pyramidApproachThere will be two different approaches based on alignments i.e. horizontal and vertical. Horizontally Inverted PyramidThis type includes the up
3 min read
JavaScript Program to Print Diamond Shape Star Pattern
This article will demonstrate how to create the diamond start pattern in JavaScript. Possible Diamond Start Patterns:Solid Diamond Start PatternHollow Diamond Star PatternInverted Hollow Diamond PatternApproach to Create Diamond Star Pattern:The approach to creating a diamond star pattern will use 2 JavaScript Nested For loops to print the upper an
3 min read
three90RightbarBannerImg