码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ Count Primes

时间:2015-04-29 13:42:50      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Description:

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

click to show more hints.

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

素数筛选法。

int countPrimes(int n) {
	bool * IsPrime = (bool*)malloc(sizeof(bool) * n);
	for (int i = 0; i < n; i++) IsPrime[i] = true;
	for (int i = 2; i < n; i++) {
		if (IsPrime[i]) {
			for (int j = i + i; j < n; j += i) {
				IsPrime[j] = false;
			}
		}
	}
	int ans = 0;
	for (int i = 2; i < n; i++) if (IsPrime[i]) ans++;
	free(IsPrime);
	return ans;
}

LeetCode OJ Count Primes

标签:leetcode

原文地址:http://blog.csdn.net/u012925008/article/details/45364005

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