![]() |
VOOZH | about |
Given a number N, the task is to print the prime numbers from 1 to N.
Examples:
Input: N = 10
Output: 2, 3, 5, 7
Explanation : The output "2, 3, 5, 7" for input N = 10 represents the list of the prime numbers less than or equal to 10.
Input: N = 5
Output: 2, 3, 5
Explanation : The output "2, 3, 5" for input N = 5 represents the list of the prime numbers less than or equal to 5.
Now, according to formal definition, a number 'n' is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1. so, we have to run a loop from 2 to n-1 and If a number is divisible by any number from 2 to n-1 it is not a prime number.
Below is the implementation of the above approach:
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(N^2),
Auxiliary Space: O(1)
For checking if a number is prime or not do we really need to iterate through all the number from 2 to n-1? We already know that a number 'n' cannot be divided by any number greater than 'n/2'. So, according to this logic we only need to iterate through 2 to n/2 since number greater than n/2 cannot divide n.
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(N2),
Auxiliary Space: O(1), since no extra space has been taken.
If a number 'n' is not divided by any number less than or equals to the square root of n then, it will not be divided by any other number greater than the square root of n. So, we only need to check up to the square root of n.
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(N^(3/2)),
Auxiliary Space: O(1)
- Create a boolean array is_prime of size (N+1), initialized with true values for all elements.
- Loop through the array is_prime from 2 to the square root of N (inclusive), and for each prime number p found in the loop:
- If is_prime[p] is true, loop through the multiples of p from p*p up to N, and mark them as false in the is_prime array.
- Loop through the array is_prime from 2 to N (inclusive), and for each index i where is_prime[i] is true, print i as a prime number.
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:
Space complexity:
In summary, the Sieve of Eratosthenes algorithm has a time complexity of O(N log(log(N))) and a space complexity of O(N) to print all the prime numbers from 1 to N.
To know more check Sieve of Eratosthenes.
One optimization of the Sieve of Eratosthenes method 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.
Below is the implementation:
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(n*log(log n)), where n is the difference between the intervals.
Space Complexity: O(n)