Given a number N, print all prime
numbers smaller than N
Input : int N = 15
Output : 2 3 5 7 11 13
Input : int N = 20
Output : 2 3 5 7 11 13 17 19
Manipulated Sieve of Eratosthenes algorithm works as follows:
For every number i where i varies from 2 to N-1:
Check if the number is prime. If the number
is prime, store it in prime array.
For every prime numbers j less than or equal to the smallest
prime factor p of i:
Mark all numbers i*p as non_prime.
Mark smallest prime factor of i*p as j
Below is the implementation of the above idea.
// C++ program to generate all prime numbers
// less than N in O(N)
constlonglongMAX_SIZE = 1000001;
// isPrime : isPrime[i] is true if number is prime
// prime : stores all prime number less than N
// SPF that store smallest prime factor of number
// [for Exp : smallest prime factor of '8' and '16'
// is '2' so we put SPF = 2 , SPF = 2 ]
vector<longlong>isprime(MAX_SIZE , true);
// function generate all prime number less than N in O(n)
// 0 and 1 are not prime
isprime = isprime = false;
// Fill rest of the entries
for(longlonginti=2; i<N ; i++)
// If isPrime[i] == True then i is
// prime number
// put i into prime vector
// A prime number is its own smallest
// prime factor
SPF[i] = i;
// Remove all multiples of i*prime[j] which are
// not prime by making isPrime[i*prime[j]] = false
// and put smallest prime factor of i*Prime[j] as prime[j]
This article is contributed by Divyanshu Srivastava and Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...