Given a quantity N, the duty is to print the primary N prime numbers.
Examples:
Enter: N = 4
Output: 2, 3, 5, 7Enter: N = 1
Output: 2
Strategy: The issue might be solved based mostly on the next concept:
Begin iterating from i = 2, until N prime numbers are discovered. For every i examine if it’s a prime or not and replace the depend of primes discovered until now.
Observe the steps talked about beneath to implement the thought:
- Create a counter variable (say X = 0) to maintain depend of primes discovered until now and an iterator (say i) to iterate by means of the optimistic integers ranging from 2.
- Iterate until X turns into N:
- Examine if i is a major or not.
- If it’s a prime, print i and improve the worth of X, in any other case, maintain X unchanged.
- Increment the worth of i by 1.
Beneath is the implementation of the above concept:
C++
// C++ code to implement the method #embody <bits/stdc++.h> utilizing namespace std; // Perform to generate first n primes void generatePrime(int n) { int X = 0, i = 2; bool flag; whereas(X < n){ flag = true; for(int j = 2; j <= sqrt(i); j++){ if (ipercentj == 0){ flag = false; break; } } if(flag){ cout << i << " "; X++; } i++; } cout << endl; } // Driver code int primary() { // Check Case 1 int N = 4; // Perform name generatePrime(N); // Check Case 2 N = 1; // Perform name generatePrime(N); return 0; }
Time Complexity: O(X * log X) the place X is the most important prime
Auxiliary House: O(1)