码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 204 Count Primes

时间:2015-06-07 20:14:20      阅读:892      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

解题思路:

空间换时间,开一个空间为n的数组,因为非素数至少可以分解为一个素数,因此遇到素数的时候,将其有限倍置为非素数,这样动态遍历+构造下来,没有被设置的就是素数。

	public int countPrimes(int n) {
		if (n <= 2)
			return 0;
		boolean[] notPrime = new boolean[n];
		int res = 0;
		int bound = (int) Math.sqrt(n);
		for (int i = 2; i < n; i++) {
			if (!notPrime[i]) {
				res++;
				if (i <= bound)
					for (int j = i * i; j < n; j += i)
						notPrime[j] = true;
			}
		}
		return res;
	}

 

Java for LeetCode 204 Count Primes

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4558911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!