【LeetCode-数学】计数质数

题目描述

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

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

题目描述: https://leetcode-cn.com/problems/count-primes/

思路1

质数就是只能被 1 和自身整除的数,1 不是质数。在判断 x 是否是质数的时候,不需要从 2 到 x-1 逐个判断能否被 x 整除,只需要在 2 到 (sqrt{x}) 范围内判断即可。代码如下:

class Solution {
public:
    int countPrimes(int n) {
        if(n==2) return 0;
        if(n==3) return 1;

        int cnt = 0;
        for(int i=2; i<n; i++){
            bool isPrime = true;
            for(int j=2; j<=i/j; j++){
                if(i%j==0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime) cnt++;
        }
        return cnt;
    }
};

思路2

厄拉多塞筛法。开一个长度为 n 的数组 v,初始值设为 true,代表 [0, n-1] 范围内的数都是质数。

  • 从 i = 2 开始循环到 n-1:
    • 如果 v[i] 是质数:
      • 计数器 cnt++;
      • 从 j = 2 开始循环到 i*j<n:v[i*j] = false;

上面的步骤可以用下图来描述

图来自这里

代码如下:

class Solution {
public:
    int countPrimes(int n) {
        if(n<=2) return 0;
        if(n==3) return 1;

        int cnt = 0;
        vector<bool> v(n, true);
        for(int i=2; i<n; i+=1){
            if(v[i]){
                for(int j=2; i*j<n; j++) v[i*j] = false;
                cnt++;
            }
        }
        return cnt;
    }
};
原文地址:https://www.cnblogs.com/flix/p/13276692.html