LeetCode知识点总结 - 204

204. Count Primes

考点 难度
Array Easy
题目

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

重点: Sieve of Eratosthenes
  1. 列出 [2, n] 所有整数;
  2. 排除不小于2的平方的所有2的倍数(4,6…);
  3. 排除不小于3的平方的所有3的倍数(9,12,15…);
  4. 以此类推,剩下的数都是质数。
答案

根据Sieve of Eratosthenes写出的答案:

public int countPrimes(int n) {
	// create a boolean array of size n
	boolean[] nums = new boolean[n];
	// set counting variable to 0
	int count = 0;
	// iterate through each element in the array
	for (int i = 2; i < n; i++) {
		// if i_th element is 'true' (meaning number i has been met previously), continue
		if (nums[i]) continue;
		// i hasn't been met, add one to count
		count += 1;
		// change false to true for multiplications of i
		for (long mult = (long)i * i; mult < n; mult += i)
			nums[(int)mult] = true;
        }
	return count;
}

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/119091484