首页 > 编程语言 > 详细

Java for LeetCode 204 Count Primes

时间:2015-06-07 20:14:08      阅读:490      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!