Java实现 LeetCode 204 计数质数

204. 计数质数

统计所有小于非负整数 n 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

class Solution {
    public int countPrimes(int n) {
		if (n < 2)
			return 0;
		boolean[] isPrime = new boolean[n];
		Arrays.fill(isPrime, true);
		for (int i = 2; i <= Math.sqrt(n); i++) {
			if (isPrime[i]) {
				for (int j = 2 * i; j < n; j += i) {
					isPrime[j] = false;
				}
			}
		}
		int count = -2;
		for (boolean bool : isPrime) {
			if (bool)
				++count;
		}
		return count;
	}
}
发布了1318 篇原创文章 · 获赞 1万+ · 访问量 103万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104501185