[Leetcode] #204 Count Primes

Discription

Count the number of prime numbers less than a non-negative number, n.

Solution

int  countPrimes(int n){ //埃拉託斯特尼篩法  2到n所有素數
	vector<bool> nums(n, true);
	for (int i = 2; i < sqrt(n); i++){
		if (!nums[i]) continue;
		int j = i*i;
		while (j < n){
			nums[j] = false;
			j += i;
		}
	}
	int result = 0;
	for (int i = 2; i < n; i++){
		if (nums[i])
			result++;
	}
	return result;
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章