This method is time out:
class Solution {
public:
int countPrimes(int n) {
int cnt = 0;
bool flag ;
for (int i = 2; i <= n; i++)
{
flag = false;
for(int j=2;j<=sqrt(i);j++)
if (i%j == 0)
{
flag = true;
break;
}
if (!flag)
cnt++;
}
return cnt;
}
};
Method Two:
class Solution {
public:
int countPrimes(int n) {
vector<bool> a(n, false);
int cnt = 0;
for (int i = 2; i < n; i++)
for (int j = 2; j*i < n; j++)
a[j*i] = true;
for (int i = 2; i < n; i++)
if (!a[i])
cnt++;
return cnt;
}
};