|
| 1 | +// Prime Sieve aka Sieve of Eratosthenes |
| 2 | +// Time complexity : O(n*log(log(n))) |
| 3 | +// Space complexity: O(n) |
| 4 | +// DESC : here we will discuss how to find prime numbers in a given range |
| 5 | +#include <bits/stdc++.h> |
| 6 | + |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +void sieve(vector<bool>& isprime, int n){ |
| 10 | + // since 0 and 1 are non-prime numbers we mark them as false; |
| 11 | + isprime[0] = isprime[1] = false; |
| 12 | + // 1st method |
| 13 | + for(int i = 2; i * i <= n; i++){ |
| 14 | + if(isprime[i] == true){ // if we find i'th number to be a prime number, we will mark every multiple of that number as non-prime |
| 15 | + for(int j = i*i ; j <= n; j += i){ // marking every multiple of i false |
| 16 | + isprime[j] = false; |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + // here we are iterating every element from 2 to sqrt(n), but since we know that 2 is the only even prime number |
| 21 | + // this can be further optimized |
| 22 | + // first we will mark every multiple of 2, and then in the next loop we will be iterating only for odd numbers |
| 23 | + // 2. more optimized approach |
| 24 | + for(int i = 2; i < 3; i++){ |
| 25 | + if(isprime[i] == true){ // if we find i'th number to be a prime number, we will mark every multiple of that number as non-prime |
| 26 | + for(int j = i*i ; j <= n; j += i){ // marking every multiple of i false |
| 27 | + isprime[j] = false; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + for(int i = 3; i * i <= n; i += 2){ // will only check for odd numbers |
| 32 | + if(isprime[i] == true){ // if we find i'th number to be a prime number, we will mark every multiple of that number as non-prime |
| 33 | + for(int j = i*i ; j <= n; j += i){// marking every multiple of i false |
| 34 | + isprime[j] = false; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + // now in the isprime vector we have prime numbers from 0 to 1000000 |
| 39 | + // note that we are using isprime vector of boolean data type and not integer as it will reduce space (integer takes 4bytes, whereas bool takes only 1byte) |
| 40 | +} |
| 41 | + |
| 42 | +signed main(){ |
| 43 | + int n=1e6; |
| 44 | + // initialize a vector isprime such that if value at an index is true then it is a prime number, else a composite |
| 45 | + // initially we consider every number as a prime number |
| 46 | + vector<bool> isprime(n+1,true); |
| 47 | + sieve(v,n); |
| 48 | + |
| 49 | + // printing prime numbers from 1 to n |
| 50 | + for( int i = 1; i <= n; i++) { |
| 51 | + if( isprime[i] == true ) |
| 52 | + cout << i << " "; |
| 53 | + } |
| 54 | + return 0; |
| 55 | +} |
0 commit comments