Tutorialspoint
Problem
Solution
Submissions

First n Prime Numbers

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 10

Write a C++ program to generate and print the first 'n' prime numbers.

Example 1
  • Input: n = 5
  • Output: "2 3 5 7 11"
  • Explanation:
    • Step 1: Initialize an empty list to store prime numbers.
    • Step 2: Start checking numbers from 2 (the first prime).
    • Step 3: For each number, check if it's divisible by any previously found prime up to its square root.
    • Step 4: If the number isn't divisible by any prime, add it to the prime list.
    • Step 5: Continue until we have found n prime numbers.
    • Step 6: Return the list of first n prime numbers: 2, 3, 5, 7, and 11.
Example 2
  • Input: n = 10
  • Output: "2 3 5 7 11 13 17 19 23 29"
  • Explanation:
    • Step 1: Initialize an empty list to store prime numbers.
    • Step 2: Start checking numbers from 2 (the first prime).
    • Step 3: For each number, check if it's divisible by any previously found prime up to its square root.
    • Step 4: If the number isn't divisible by any prime, add it to the prime list.
    • Step 5: Continue until we have found n prime numbers.
    • Step 6: Return the list of first n prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.
Constraints
  • 1 ≤ n ≤ 10^4
  • Output should be space-separated prime numbers
  • Time Complexity: O(n * sqrt(n))
  • Space Complexity: O(n)
NumberVariables and Data TypesWiproGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a helper function to check primality
  • Store primes in a list until reaching count n
  • Optimize divisor checks up to sqrt(num)

Steps to solve by this approach:

 Step 1: Create a vector to store found prime numbers.

 Step 2: Start checking numbers from 2 (the first prime number).
 Step 3: For each number, check if it's divisible by any integer from 2 to its square root.
 Step 4: If no divisors are found, add the number to the prime numbers vector.
 Step 5: Continue until we find the requested number of primes.
 Step 6: Print all the prime numbers found in the vector.
 Step 7: Return from the function.

Submitted Code :