Program to print prime numbers from 1 to N. (original) (raw)

Last Updated : 12 Jul, 2025

Given a number N, the task is to print the prime numbers from 1 to N.
**Examples:

**Input: N = 10
**Output: 2, 3, 5, 7
**Explanation : The output "2, 3, 5, 7" for input N = 10 represents the list of the prime numbers less than or equal to 10.

**Input: N = 5
**Output: 2, 3, 5
**Explanation : The output "2, 3, 5" for input N = 5 represents the list of the prime numbers less than or equal to 5.

Algorithm to print prime numbers:

Approach 1: Print prime numbers using loop.

Now, according to formal definition, a number 'n' is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1. so, we have to run a loop from 2 to n-1 and If a number is divisible by any number from 2 to n-1 it is not a prime number.

Below is the implementation of the above approach:

C++ `

// C++ program to display Prime numbers till N #include <bits/stdc++.h> using namespace std;

// function to check if a given number is prime bool isPrime(int n) { // since 0 and 1 is not prime return false. if (n == 1 || n == 0) return false;

// Run a loop from 2 to n-1
for (int i = 2; i < n; i++) {
    // if the number is divisible by i, then n is not a
    // prime number.
    if (n % i == 0)
        return false;
}
// otherwise, n is prime number.
return true;

}

// Driver code int main() { int N = 100;

// check for every number from 1 to N
for (int i = 1; i <= N; i++) {
    // check if current number is prime
    if (isPrime(i))
        cout << i << " ";
}

return 0;

}

C

// C program to display Prime numbers till N #include <stdbool.h> #include <stdio.h>

// function to check if a given number is prime bool isPrime(int n) { // since 0 and 1 is not prime return false. if (n == 1 || n == 0) return false;

// Run a loop from 2 to n-1
for (int i = 2; i < n; i++) {
    // if the number is divisible by i, then n is not a
    // prime number.
    if (n % i == 0)
        return false;
}
// otherwise, n is prime number.
return true;

}

// Driver code int main() { int N = 100;

// check for every number from 1 to N
for (int i = 1; i <= N; i++) {
    // check if current number is prime
    if (isPrime(i))
        printf("%d ", i);
}

return 0;

}

// This code is contributed by Sania Kumari Gupta

Java

// Java program to display Prime numbers till N class GFG { //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false;

      //Run a loop from 2 to n-1
      for(int i=2; i<n; i++){
        // if the number is divisible by i, then n is not a prime number.
            if(n%i==0)return false;
      }
      //otherwise, n is prime number.
      return true;
}


// Driver code 
public static void main (String[] args) 
{ 
    int N = 100; 
    //check for every number from 1 to N
    for(int i=1; i<=N; i++){
        //check if current number is prime
        if(isPrime(i)) {
            System.out.print(i + " ");
        }
    }

}

}

Python

Python3 program to display Prime numbers till N

#function to check if a given number is prime def isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False

#Run a loop from 2 to n-1 for i in range(2,n): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False

#otherwise, n is prime number. return True

Driver code

N = 100; #check for every number from 1 to N for i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=" ")

C#

// C# program to display Prime numbers till N using System;

class GFG {

 //function to check if a given number is prime
 static bool isPrime(int n){
    //since 0 and 1 is not prime return false.
    if(n==1||n==0) return false;

    //Run a loop from 2 to n-1
    for(int i=2; i<n; i++) {
        // if the number is divisible by i, then n is not a prime number.
        if(n%i==0) return false;
    }
  //otherwise, n is prime number.
  return true;
}

// Driver code 
public static void Main (String[] args) 
{ 
    int N = 100; 
    //check for every number from 1 to N
    for(int i=1; i<=N; i++) {
      //check if current number is prime
        if(isPrime(i)) {
          Console.Write(i + " "); 
        }
    }

}

}

// This code is contributed by Rajput-Ji

JavaScript

// JavaScript program to display Prime numbers till N

// function to check if a given number is prime function isPrime(n) { // since 0 and 1 is not prime return false. if (n == 1 || n == 0) return false;

// Run a loop from 2 to n-1
for (var i = 2; i < n; i++) {
    // if the number is divisible by i, then n is not a prime number.
    if (n % i == 0) return false;
}
// otherwise, n is prime number.
return true;

}

// Driver code var N = 100;

// check for every number from 1 to N var result = []; for (var i = 1; i <= N; i++) { // check if current number is prime if (isPrime(i)) { result.push(i); } }

console.log(result.join(' '));

`

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

**Time Complexity: O(N^2),
**Auxiliary Space: O(1)

Approach 2: Optimize the first approach

For checking if a number is prime or not do we really need to iterate through all the number from 2 to n-1? We already know that a number 'n' cannot be divided by any number greater than 'n/2'. So, according to this logic we only need to iterate through 2 to n/2 since number greater than n/2 cannot divide n.

C++ `

// C++ program to display Prime numbers till N #include <bits/stdc++.h> using namespace std;

//function to check if a given number is prime bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false;

//Run a loop from 2 to n/2.
for(int i=2; i<=n/2; i++) {
      // if the number is divisible by i, then n is not a prime number.
      if(n%i==0) return false;
}
//otherwise, n is prime number.
return true;

}

// Driver code int main() { int N = 100;

//check for every number from 1 to N
  for(int i=1; i<=N; i++){
    //check if current number is prime
    if(isPrime(i)) {
      cout << i << " ";
    }
}

return 0;

}

Java

// Java program to display // Prime numbers till N class GFG { //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false;

    //Run a loop from 2 to n-1
    for(int i=2; i<=n/2; i++){
        // if the number is divisible by i, then n is not a prime number.
        if(n%i==0)return false;
    }
    //otherwise, n is prime number.
    return true;
}


// Driver code 
public static void main (String[] args) 
{ 
    int N = 100; 
    //check for every number from 1 to N
    for(int i=1; i<=N; i++){
        //check if current number is prime
        if(isPrime(i)) {
          System.out.print(i + " ");
        }
    }

}

}

Python

Python3 program to display Prime numbers till N

#function to check if a given number is prime def isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False

#Run a loop from 2 to n/2 for i in range(2,(n//2)+1):

        #if the number is divisible by i, then n is not a prime number.
    if(n%i==0):
        return False

#otherwise, n is prime number. return True

Driver code

N = 100; #check for every number from 1 to N for i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=" ")

C#

// C# program to display // Prime numbers till N using System;

class GFG {

//function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false;

  //Run a loop from 2 to n/2.
  for(int i=2; i<=n/2; i++){
    // if the number is divisible by i, then n is not a prime number.
    if(n%i==0)return false;
  }

//otherwise, n is prime number. return true; }

// Driver code public static void Main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + " "); } }

} }

// This code is contributed by Rajput-Ji

JavaScript

`

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

**Time Complexity: O(N2),
**Auxiliary Space: O(1),since no extra space has been taken.

Approach 3:

If a number 'n' is not divided by any number less than or equals to the square root of n then, it will not be divided by any other number greater than the square root of n. So, we only need to check up to the square root of n.

C++ `

// C++ program to display Prime numbers till N #include <bits/stdc++.h> using namespace std;

//function to check if a given number is prime bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false;

//Run a loop from 2 to square root of n. for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; }

// Driver code int main() { int N = 100;

//check for every number from 1 to N
  for(int i=1; i<=N; i++){
  //check if current number is prime
  if(isPrime(i)) {
    cout << i << " ";
  }
}

return 0;

}

Java

// Java program to display // Prime numbers till N class GFG { //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false;

//Run a loop from 2 to square root of n for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; }

// Driver code public static void main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + " "); } }

} }

Python

Python3 program to display Prime numbers till N

function to check if a given number is prime

def isPrime(n): # since 0 and 1 is not prime return false. if n == 1 or n == 0: return False

# Run a loop from 2 to square root of n.
for i in range(2, int(n**(1/2)) + 1):
    # if the number is divisible by i, then n is not a prime number.
    if n % i == 0:
        return False

# otherwise, n is a prime number.
return True

Driver code

N = 100

check for every number from 1 to N

for i in range(1, N + 1): # check if the current number is prime if isPrime(i): print(i, end=" ")

C#

// C# program to display // Prime numbers till N using System;

class GFG {

//function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false;

  //Run a loop from 2 to square root of n.
  for(int i=2; i*i<=n; i++){
    // if the number is divisible by i, then n is not a prime number.
    if(n%i==0)return false;
  }

//otherwise, n is prime number. return true; }

// Driver code public static void Main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + " "); } }

} }

// This code is contributed by Rajput-Ji

JavaScript

`

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

Time Complexity: O(N^(3/2)),
**Auxiliary Space: O(1)

Approach 4: Sieve of Eratosthenes Algorithm

  1. Create a boolean array is_prime of size (N+1), initialized with true values for all elements.
  2. Loop through the array is_prime from 2 to the square root of N (inclusive), and for each prime number p found in the loop:
  1. Loop through the array is_prime from 2 to N (inclusive), and for each index i where is_prime[i] is true, print i as a prime number.

C++ `

// CPP program to print prime numbers from 1 to N // using Sieve of Eratosthenes #include <bits/stdc++.h> using namespace std;

void sieve_of_eratosthenes(int n) { bool is_prime[n + 1]; memset(is_prime, true, sizeof(is_prime)); is_prime[0] = is_prime[1] = false; for (int p = 2; p * p <= n; p++) { if (is_prime[p]) { for (int i = p * p; i <= n; i += p) { is_prime[i] = false; } } } for (int i = 2; i <= n; i++) { if (is_prime[i]) { cout << i << " "; } } }

int main() { sieve_of_eratosthenes(100); return 0; }

// This code is contributed by Susobhan Akhuli

Java

// Java program to print prime numbers from 1 to N // using Sieve of Eratosthenes

import java.util.*;

public class GFG { public static void sieve_of_eratosthenes(int n) { boolean[] is_prime = new boolean[n + 1]; Arrays.fill(is_prime, true); is_prime[0] = is_prime[1] = false; for (int p = 2; p * p <= n; p++) { if (is_prime[p]) { for (int i = p * p; i <= n; i += p) { is_prime[i] = false; } } } for (int i = 2; i <= n; i++) { if (is_prime[i]) { System.out.print(i + " "); } } }

public static void main(String[] args)
{
    sieve_of_eratosthenes(100);
}

}

// This code is contributed by Susobhan Akhuli

Python

Python program to print prime numbers from 1 to N

using Sieve of Eratosthenes

def sieve_of_eratosthenes(n): is_prime = [True] * (n+1) is_prime[0] = is_prime[1] = False for p in range(2, int(n*0.5)+1): if is_prime[p]: for i in range(pp, n+1, p): is_prime[i] = False for i in range(2, n+1): if is_prime[i]: print(i, end=' ')

sieve_of_eratosthenes(100)

This code is contributed by Susobhan Akhuli

C#

// C# program to print prime numbers from 1 to N // using Sieve of Eratosthenes using System;

public class GFG { // Function to find prime numbers from 1 // to N static public void sieve_of_eratosthenes(int n) { // Create a boolean array "is_prime[0..n]" and // initialize all entries as true. A value in // is_prime[i] will finally be false if i is Not a // prime, else true bool[] is_prime = new bool[n + 1]; Array.Fill(is_prime, true);

    // Mark 0 and 1 as false as they are not prime
    is_prime[0] = is_prime[1] = false;

    // Traverse through all numbers starting from 2, as
    // 1 is not prime
    for (int p = 2; p * p <= n; p++) {
        // If is_prime[p] is not changed, then it is a
        // prime
        if (is_prime[p]) {
            // Update all multiples of p as not prime
            for (int i = p * p; i <= n; i += p) {
                is_prime[i] = false;
            }
        }
    }

    // Print all prime numbers
    for (int i = 2; i <= n; i++) {
        if (is_prime[i]) {
            Console.Write(i + " ");
        }
    }
}

static public void Main()
{
    // Call sieve_of_eratosthenes() function with value
    // 100
    sieve_of_eratosthenes(100);
}

}

JavaScript

// JavaScript program to print prime numbers from 1 to N // using Sieve of Eratosthenes

function sieve_of_eratosthenes(n) { // Create a boolean array "is_prime[0..n]" and // initialize all entries as true. A value in // is_prime[i] will finally be false if i is Not a // prime, else true let is_prime = new Array(n + 1).fill(true);

// Mark 0 and 1 as false as they are not prime is_prime[0] = is_prime[1] = false;

// Traverse through all numbers starting from 2, as // 1 is not prime for (let p = 2; p * p <= n; p++) { // If is_prime[p] is not changed, then it is a // prime if (is_prime[p]) { // Update all multiples of p as not prime for (let i = p * p; i <= n; i += p) { is_prime[i] = false; } } }

// Print all prime numbers for (let i = 2; i <= n; i++) { if (is_prime[i]) { document.write(i+" "); } } }

// Call sieve_of_eratosthenes() function with value // 100 sieve_of_eratosthenes(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

Complexity Analysis:

**Time complexity:

**Space complexity:

In summary, the Sieve of Eratosthenes algorithm has a time complexity of O(N log(log(N))) and a space complexity of O(N) to print all the prime numbers from 1 to N.

To know more check **Sieve of Eratosthenes.

Optimized Sieve of Eratosthenes Method: (Bitwise Sieve Method)

One optimization of the Sieve of Eratosthenes method is, we have skipped all even numbers altogether. We reduce the size of the prime array to half. We also reduce all iterations to half.

Steps:

  1. Create a boolean array prime of size ****(n/2)**, initialized with false values for all elements.
  2. As except **2, there are not any even prime numbers, so we skip **2 and then check for only **odd numbers, so that we just have to check half elements.
  3. Inside the loop:
    1. In each iteration, if **prime[i/2] is **false, then loop through the multiples of **i from **i*i up to **N with increment of **2*i, and mark them as **true in the prime array.
  4. Finally, first print **2 and then loop through the array prime from **3 to **N (inclusive), and for each index **i/2 where **prime[i/2] is false, print **i as a prime number.

Below is the implementation:

C++ `

// CPP program to print prime numbers from 1 to N // using simple optimized Sieve of Eratosthenes // to reduce size of prime array to half and // reducing iterations. #include <bits/stdc++.h> using namespace std;

void normalSieve(int n) { // prime[i] is going to store true if // if i*2 + 1 is composite. bool prime[n / 2]; memset(prime, false, sizeof(prime));

// 2 is the only even prime so we can
// ignore that. Loop starts from 3.
for (int i = 3; i * i < n; i += 2) {
    // If i is prime, mark all its
    // multiples as composite
    if (prime[i / 2] == false)
        for (int j = i * i; j < n; j += i * 2)
            prime[j / 2] = true;
}

// writing 2 separately
printf("2 ");

// Printing other primes
for (int i = 3; i < n; i += 2)
    if (prime[i / 2] == false)
        printf("%d ", i);

}

// Driver code int main() { int n = 100; normalSieve(n); return 0; }

// This code is contributed by Susobhan Akhuli

Java

import java.util.Arrays;

class GFG { // Function to find prime numbers up to 'n' using // the normal Sieve of Eratosthenes algorithm public static void normalSieve(int n) { // Create a boolean array to mark non-prime numbers, // starting from 3 up to n // Since we only need to consider odd numbers // (except for 2), we use n/2 elements in the array. boolean[] prime = new boolean[n / 2];

    // Initialize all elements as false 
  // (considering all numbers as potential primes initially)
    Arrays.fill(prime, false);

    // Iterate over odd numbers starting from 3 
  // up to the square root of n
    // Since any composite number has a prime factor 
  // less than or equal to its square root,
    // we only need to check up to the square root to 
  // find all primes.
    for (int i = 3; i * i < n; i += 2) {
        // If 'i' is marked as non-prime (prime[i/2] is true), 
      // skip to the next iteration
        if (!prime[i / 2]) {
            // Mark all multiples of 'i' as non-prime by 
          // setting their corresponding positions in the array to true
            // We start marking from i*i since all smaller multiples of 'i' 
          // would have been marked by previous primes.
            for (int j = i * i; j < n; j += i * 2) {
                prime[j / 2] = true;
            }
        }
    }

    // Print the prime numbers
    System.out.print("2 "); // 2 is the only even prime number
    for (int i = 3; i < n; i += 2) {
        if (!prime[i / 2]) {
            System.out.print(i + " "); // If prime[i/2] is false, 'i' is a prime number, so print it.
        }
    }
}

public static void main(String[] args) {
    int n = 100;
    normalSieve(n); // Find and print prime numbers up to 'n'
}

}

Python

def normal_sieve(n): # prime[i] is going to store True if # i * 2 + 1 is composite. prime = [False] * (n // 2)

# 2 is the only even prime, so we can
# ignore that. Loop starts from 3.
for i in range(3, int(n**0.5) + 1, 2):
    # If i is prime, mark all its
    # multiples as composite
    if not prime[i // 2]:
        for j in range(i * i, n, i * 2):
            prime[j // 2] = True

# Print 2 separately
print(2, end=" ")

# Printing other primes
for i in range(3, n, 2):
    if not prime[i // 2]:
        print(i, end=" ")

Driver code

if name == "main": n = 100 normal_sieve(n)

C#

using System;

public class MainClass { public static void NormalSieve(int n) { // prime[i] is going to store true if // if i*2 + 1 is composite. bool[] prime = new bool[n / 2]; Array.Fill(prime, false);

    // 2 is the only even prime so we can ignore that.
    // Loop starts from 3.
    for (int i = 3; i * i < n; i += 2)
    {
        // If i is prime, mark all its multiples as composite
        if (!prime[i / 2])
        {
            for (int j = i * i; j < n; j += i * 2)
            {
                prime[j / 2] = true;
            }
        }
    }

    // writing 2 separately
    Console.Write("2 ");

    // Printing other primes
    for (int i = 3; i < n; i += 2)
    {
        if (!prime[i / 2])
        {
            Console.Write(i + " ");
        }
    }
}

public static void Main(string[] args)
{
    int n = 100;
    NormalSieve(n);
}

}

JavaScript

function normalSieve(n) { // prime[i] is going to store true if i*2 + 1 is composite. let prime = new Array(n / 2).fill(false);

// 2 is the only even prime so we can ignore that.
// Loop starts from 3.
for (let i = 3; i * i < n; i += 2) {
    // If i is prime, mark all its multiples as composite
    if (!prime[Math.floor(i / 2)]) {
        for (let j = i * i; j < n; j += i * 2) {
            prime[Math.floor(j / 2)] = true;
        }
    }
}

// Writing 2 separately
document.write("2 ");

// Printing other primes
for (let i = 3; i < n; i += 2) {
    if (!prime[Math.floor(i / 2)]) {
        document.write(i + " ");
    }
}

}

// Main code to test the function

let n = 100; normalSieve(n);

`

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

**Time Complexity: O(n*log(log n)), where n is the difference between the intervals.
**Space Complexity: O(n)