The Wayback Machine - https://web.archive.org/web/20230117045203/https://www.geeksforgeeks.org/generate-and-print-first-n-prime-numbers/
Skip to content
Related Articles

Related Articles

Generate and print first N prime numbers

Improve Article
Save Article
  • Last Updated : 04 Jan, 2023
Improve Article
Save Article

Given a number N, the task is to print the first N prime numbers.

Examples: 

Input: N = 4
Output: 2, 3, 5, 7

Input: N = 1
Output: 2

Approach: The problem can be solved based on the following idea:

Start iterating from i = 2, till N prime numbers are found. For each i check if it is a prime or not and update the count of primes found till now.

Follow the steps mentioned below to implement the idea:

  • Create a counter variable (say X = 0) to keep count of primes found till now and an iterator (say i) to iterate through the positive integers starting from 2.
  • Iterate till X becomes N:
    • Check if i is a prime or not.
    • If it is a prime, print i and increase the value of X, otherwise, keep X unchanged.
    • Increment the value of i by 1.

Below is the implementation of the above idea:

C++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to generate first n primes
void generatePrime(int n)
{
    int X = 0, i = 2;
    bool flag;
    while(X < n){
        flag = true;
        for(int j = 2; j <= sqrt(i); j++){
            if (i%j == 0){
                flag = false;
                break;
            }
        }
        if(flag){
            cout << i << " ";
            X++;
        }
        i++;
    }
    cout << endl;
}

// Driver code
int main()
{
    // Test Case 1
    int N = 4;

    // Function call
    generatePrime(N);
  
    // Test Case 2
    N = 1;
  
    // Function call
    generatePrime(N);
  
    return 0;
}
Output

2 3 5 7 
2 

Time Complexity: O(X * log X) where X is the largest prime
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!