bincodes

以下内容除代码外为转载 LeetCode官方题解给出的解释:
官方释义传送
在这里插入图片描述

厄拉多塞筛选法

class Solution {
public:
    int countPrimes(int n) {
		vector<int> help(n,1);
		int count = 0;
		for (int i = 2; i < n; i++) {
			if (help[i] == 1) {
				count++;
				if ((long long)i * i < n) {
					for (int j = i + i; j < n; j += i) {
						help[j] = 0;//质数的倍数不是质数
					}
				}
			}
		}
		return count;
    }
};

线性筛

在这里插入图片描述

class Solution {
public:
    int countPrimes(int n) {
		vector<int> prime;
		vector<int> IsPrime(n, 1);
		for (int i = 2; i < n; i++) {
            //数组值为1为质数
			if (IsPrime[i]) {
				prime.push_back(i);
			}
			for (int j = 0; j < prime.size() && i * prime[j] < n; j++) {//处理prime数组中的元素,实行标记
				IsPrime[i * prime[j]] = 0;
				if (i % prime[j] == 0)
					break;
			}
		}

		return prime.size();
    }
};

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2021-11-02
  • 2021-11-02
  • 2021-10-21
  • 2021-12-04
  • 2021-11-17
  • 2021-11-17
猜你喜欢
  • 2021-11-17
  • 2021-11-17
  • 2021-11-17
  • 2021-11-17
  • 2021-11-12
  • 2021-11-02
  • 2021-11-12
相关资源
相似解决方案