204. Count prime number

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;
	}
};

 

Published 114 original articles · won praise 1 · views 4647

Guess you like

Origin blog.csdn.net/weixin_40823740/article/details/103950060
Recommended