![]() |
VOOZH | about |
š C Program to Display Prime Numbers Between Intervals
Given two numbers a and b as interval range, the task is to find the prime numbers in between this interval.
Examples:
Input: a = 1, b = 10 Output: 2, 3, 5, 7 Input: a = 10, b = 20 Output: 11, 13, 17, 19
In the below program, the range of numbers is taken as input and stored in the variables 'a' and 'b'. Then using for-loop, the numbers between the interval of a and b are traversed. For each number in the for loop, it is checked if this number is prime or not. If found prime, print the number. Then the next number in the loop is checked, till all numbers are checked.
Program:
Output:
Enter lower bound of the interval: 1 Enter upper bound of the interval: 10 Prime numbers between 1 and 10 are: 2 3 5 7
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.
Below is the implementation of the above approach:
Prime numbers between 1 and 10 are: 2 3 5 7
Time Complexity: O(N*sqrt(N)), where max value of N is b.
Auxiliary Space: O(1), since no extra space has been taken.
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than N when N is smaller than 10 million or so.
Below is the implementation of the above approach:
2 3 5 7
Time Complexity:
The time complexity of the Sieve of Eratosthenes algorithm is O(n*log(log(n))) as it iterates over all numbers from 2 to n and removes all the multiples of each prime number.
Auxiliary Space:
The space complexity of the algorithm is O(n), which is the size of the boolean array prime.