3233. Find the Count of Numbers Which Are Not Special

class Solution {
public:
    int nonSpecialCount(int l, int r)
    {
        int limit = (int)(sqrt(r));

        vector<bool> isPrime(limit + 1, true);
        isPrime[0] = isPrime[1] = false;

        for (int i = 2; i * i <= limit; i++)
        {
            if (isPrime[i])
            {
                for (int j = i * i; j <= limit; j += i)
                {
                    isPrime[j] = false;
                }
            }
        }

        int cnt = 0;
        for (int i = 2; i <= limit; i++)
        {
            if (isPrime[i])
            {
                int square = i * i;
                if (l <= square && square <= r)
                {
                    cnt++;
                }
            }
        }

        int total = r - l + 1;

        return total - cnt;
    }
};
  • T: O(R)O(\sqrt R)
  • S: O(R)O(\sqrt R)