<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:

    int countPrimes(int n) {
        if (n < 3) return 0;
        if (n == 3) return 1;

        int sqrtn = usqrt4(n-1);
        int smallPrimes[sqrtn];
        int smallPrimeCount = 0;

        for(int i = 2; i <= sqrtn; i++) {
            bool isPrime = true;
            int p = 0;
            int sqrti = usqrt4(i);
            for(int j = 0; j < smallPrimeCount - 1 && p <= sqrti && isPrime; j++) {
                p = smallPrimes[j];
                if (i % p == 0) isPrime = false;
            }
            if (isPrime) {
                smallPrimes[smallPrimeCount] = i;
                smallPrimeCount++;
            }
        }
        int primeCount = (n - 2) + smallPrimeCount + adjust(smallPrimes, smallPrimeCount, n, 1, -1, 0);
        //cout << smallPrimeCount;
        return primeCount;
    }

private: 

    int adjust(int* primes, int numPrimes, int n, int base, int sign, int start) {
        int adj = 0;
        for (int i = start; i < numPrimes; i++) {
            int num = base * primes[i];
            if (num >= n) break;
            //System.out.println("base: " + base + " - p: " + primes[i] + " - num: " + num + " - adj: " + (sign * ((n-1) / num)));
            adj += sign * ((n-1) / num);
            if (i + 1 < numPrimes && num <= n / primes[i+1]) {
                adj += adjust(primes, numPrimes, n, num, ~sign + 1, i+1);
            }
        }

        return adj;
    }

    static unsigned usqrt4(int val) {
        int a, b;

        if (val < 2) return val; /* avoid div/0 */
        if (val < 9) return 2;

        a = 300;       /* starting point is relatively unimportant */

        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        b = val / a; a = (a+b) /2;
        //b = val / a; a = (a+b) /2;

        return a;
    }
};
7980