![]() |
VOOZH | about |
Given a number n, print all primes smaller than n.
Examples :
Input : 30 Output : 2 3 5 7 11 13 17 19 23 29 Input : n = 100 Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
We know how to calculate all primes less than n by the Sieve of Eratosthenes. Below is an implementation of Sieve.
One optimization in the below implementation is, we have skipped all even numbers altogether.
We reduce the size of the prime array to half. We also reduce all iterations to half.
Output :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(nlogn)
Space Complexity: O(n)
Further optimization using bitwise operators.
The above implementation uses bool data type which takes 1 byte. We can optimize space to n/8 by using individual bits of an integer to represent individual primes. We create an integer array of size n/64. Note that the size of the array is reduced to n/64 from n/2 (Assuming that integers take 32 bits).
Output:
2 3 5 7 11 13 17 19 23 29
Time Complexity: O(nlogn)
Space Complexity: O(n)