<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 10
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li>
</ul>

class Solution {
public:
    //Sieve of eratosthenes
/*  int countPrimes(int n) {
        int count=0;
        vector<bool> arr(n+1,true);
        arr[0]=arr[1]=false;
        for(int i=2;i<n;i++)
        {
            if (arr[i]==true)
                {count++;
                for(int j=2*i;j<n;j=j+i)
                {
                    arr[j]=false;
                }
                }
        }
        return count;
    } */

    //To find primes less than n
    void simpleSieve(int n, vector<int> &ans){
        vector<bool> arr(n+1,true);
        arr[0]=arr[1]=false;
        for(int i=2;i<n;i++)
        {
            if (arr[i]==true)
                {ans.push_back(i);
                for(int j=2*i;j<n;j=j+i)
                {
                    arr[j]=false;
                }
                }
        }
    }
    int countPrimes(int n){
        
        int count=0;
        
        //Step1: Find all primes till sqrt(n);
        vector<int> primes;
        int target= floor(sqrt(n)) + 1;
        simpleSieve(target , primes);

        //Step2: Segment the sieve into [L,R] segments
        int L= target; int R= 2*target;
        while(L < n){
            if(R > n) R= n;
            vector<bool> temp(R-L , true);
            for(auto pr: primes){
                int firstMultiple= floor(L/pr * pr);
                if(firstMultiple < L) firstMultiple += pr;
                for(int i= firstMultiple; i<R; i+=pr) 
                    temp[i-L]= false;
            }

            for(int i=L; i<R; i++){
                if(temp[i-L] == true) count++;
            }

            L += target;
            R += target; 
        }

        return count += primes.size();
    }
};
15780