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