1. 程式人生 > >每天一道LeetCode-----計算小於n的素數個數

每天一道LeetCode-----計算小於n的素數個數

Count Primes

計算小於n的素數個數

思路:

如果一個數m是素數,那麼所有m * k就都不是素數。另外2是最小的素數

程式碼如下

class Solution {
public:
    int countPrimes(int n) {
        vector<int> nums(n 1);
        int count{0};
        for(int i = 2; i < n; ++i) {
            if(nums[i]) {
                ++count;
                for
(int j = 2; i * j < n; ++j) { nums[i * j] = 0; } } } return count; } };