Given an integer n, list all prime numbers from 2 through n in ascending order. Include n if it is prime.
A prime number is an integer greater than 1 with exactly two positive divisors, 1 and itself. The primeTillN function returns the list, and the driver prints it.
Example 1
Input: n = 7
Output: [2, 3, 5, 7]
Explanation: The numbers 2, 3, 5, and 7 each have exactly two positive divisors. The remaining candidates, 4 and 6, are divisible by 2.
Example 2
Input: n = 2
Output: [2]
Explanation: 2 is the smallest prime and is included because the upper bound is inclusive.
Brute Force Approach
A prime number has exactly two positive divisors, 1 and itself. We can check every number from 2 through n, count its divisors, and keep it if the count is exactly 2.
Divisors come in pairs. If d divides x, then x / d also divides x. For example, the divisor pairs of 6 are (1, 6) and (2, 3). At least one value in each pair is at most √x, so checking divisors up to √x lets us find every pair.
For a perfect square, the two values in the middle pair are equal and must be counted only once. For example, 4 has the pairs (1, 4) and (2, 2), giving three distinct divisors. Since its divisor count is greater than 2, it is not prime.
Approach
Initialise an empty list to store the prime numbers.
Check each number
xfrom2throughn, inclusive.Reset the divisor count to
0for each number.Try each divisor
dfrom1through√x. Ifddividesx, count bothdandx / d. Count only one if they are equal.Append
xto the list if its divisor count is exactly2.Return the list after checking all numbers.
Dry Run
Print All Primes Till N Brute force
Solution
#include <bits/stdc++.h>using namespace std;class Solution {private: // A prime number has exactly two distinct positive divisors. bool isPrime(int number) { int divisorCount = 0; // Check up to the square root. Division avoids overflow. for (int divisor = 1; divisor <= number / divisor; ++divisor) { if (number % divisor == 0) { int pairedDivisor = number / divisor; // Count both divisors, or just one if they are equal. divisorCount += (divisor == pairedDivisor ? 1 : 2); } } return divisorCount == 2; }public: // Return all prime numbers from 2 through n in ascending order. vector<int> primeTillN(int n) { vector<int> primes; // A long long counter can safely step past INT_MAX. for (long long number = 2; number <= n; ++number) { if (isPrime(number)) { primes.push_back(number); } } return primes; }};int main() { Solution solution; int n = 7; vector<int> primes = solution.primeTillN(n); // Prints 2 3 5 7. for (int prime : primes) { cout << prime << ' '; } cout << '\n'; return 0;}Complexity Analysis
Time Complexity : O(N√N). Each candidate X takes O(√X) time to check.
Space Complexity : O(1) auxiliary space. The returned vector holds π(N) primes, where π(N) is approximately N / log N for large N.
Optimal Approach
Instead of checking each number separately, use each prime number to mark its multiples as composite. For example, once we know 2 is prime, we can mark 4, 6, 8, and the remaining multiples of 2 up to n. Next, 3 starts marking at 9, then continues with 12, 15, and so on.
When we reach an unmarked number, it must be prime. If it were composite, one of its smaller prime factors would have marked it already. This method is called the Sieve of Eratosthenes.
For each prime p, start marking from p × p. Smaller multiples already have a smaller prime factor and have been marked earlier. For example, when processing 5, the multiples 10, 15, and 20 have already been marked by 2 or 3, so we start at 25.
Approach
If
n < 2, return an empty list.Create an
isPrimearray of sizen + 1and initialise all entries totrue.Set
isPrime[0]andisPrime[1]tofalsebecause neither number is prime.Scan each number
pfrom2throughn. IfisPrime[p]isfalse, skip it. Otherwise, appendpto the result.For each prime
pfound in step 4, mark its multiples fromp × pthroughnasfalse, increasing the multiple bypeach time.Return the result. Scanning from left to right adds the primes in ascending order.
Dry Run
Print All Primes Till N Optimal
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: vector<int> primeTillN(int n) { // There are no prime numbers smaller than 2. if (n < 2) { return {}; } // Initially, assume every number from 0 to n is prime. vector<bool> isPrime(n + 1, true); // 0 and 1 are not prime numbers. isPrime[0] = false; isPrime[1] = false; // Stores all prime numbers found. vector<int> primes; // Check every number from 2 to n. for (long long p = 2; p <= n; ++p) { // If p was already marked, it is not prime. if (!isPrime[p]) { continue; } // p is prime, so add it to the answer. primes.push_back(p); // Mark all multiples of p as non-prime. // Start from p * p because smaller multiples // have already been marked by smaller primes. for (long long multiple = p * p; multiple <= n; multiple += p) { isPrime[multiple] = false; } } // Return all prime numbers in increasing order. return primes; }};int main() { Solution solution; int n = 7; // Find all prime numbers from 2 to n. vector<int> primes = solution.primeTillN(n); // Print the prime numbers. for (int prime : primes) { cout << prime << ' '; } cout << '\n'; return 0;}Complexity Analysis
Time Complexity : O(N log log N) for marking multiples, plus O(N) to scan the candidates. The total is O(N log log N).
Space Complexity : O(N) auxiliary space for the sieve. The returned vector also holds π(N) primes.
Interview follow-up Questions
An empty vector. The smallest prime is 2.
Be the first to add a comment.