LeetCode

◇◆丶佛笑我妖孽 提交于 2020-12-27 17:24:23

Topic

  • Hash Table
  • Math

Description

https://leetcode.com/problems/count-primes/

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

Example 1:

Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Example 2:

Input: n = 0
Output: 0

Example 3:

Input: n = 1
Output: 0

Constraints:

  • 0 <= n <= 5 * 10⁶

Analysis

埃拉托色尼筛选法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数,它的容斥原理之完备性条件是p=H~。埃拉托色尼筛选法_百度百科

Submission

public class CountPrimes {
	public int countPrimes(int n) {
		boolean[] notPrime = new boolean[n];
		int count = 0;

		for (int i = 2; i &lt; n; i++) {
			if (!notPrime[i]) {
				count++;
				for (int j = i; i * j &lt; n; j++) {
					notPrime[i * j] = true;
				}
			}
		}
		return count;
	}
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class CountPrimesTest {

	@Test
	public void test() {
		CountPrimes obj = new CountPrimes();

		assertEquals(4, obj.countPrimes(10));
		assertEquals(0, obj.countPrimes(0));
		assertEquals(0, obj.countPrimes(1));
	}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!