Prime numbers in a given range using STL | Set 2
Generate all prime numbers between two given numbers. The task is to print prime numbers in that range. The Sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n where n is smaller than 10 million or so.
Input : start = 50 end = 100 Output : 53 59 61 67 71 73 79 83 89 97 Input : start = 900 end = 1000 Output : 907 911 919 929 937 941 947 953 967 971 977 983 991 997
Idea is to use Sieve of Eratosthenes as a subroutine. We have discussed one implementation in Prime numbers in a given range using STL | Set 1
- Find primes in the range from 0 to end and store it in a vector
- Find the index of element less than start value using binary search. We use lower_bound() in STL.
- Erase elements from the beginning of the vector to that index. We use vector erase()
Viola! The vector contains primes ranging from start to end.
53 59 61 67 71 73 79 83 89 97
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.