初级算法之数学:计算质数

统计所有小于非负整数 n 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。

传统方法不说了,这里选择效率更高的筛选法:
从质数2开始,凡是2的倍数全为false,再依次到n-1,把所有的倍数全都筛选出来。

int countPrimes(int n) {
	bool *cnt = new bool[n];
	int count = 0;
	for (int i = 0; i < n ; i++) cnt[i] = true;
	for (int i = 2; i < n; i++) {
		if (cnt[i] == true) {
			count++;
			for (int j = 2 * i; j < n ; j += i) cnt[j] = false;
		}
	}
	return count;
}

发布了30 篇原创文章 · 获赞 0 · 访问量 1115

猜你喜欢

转载自blog.csdn.net/qq_41220834/article/details/104068057