首页 > 其他 > 详细

LeetCode OJ Count Primes

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!