1. 程式人生 > >leetcode-204-Count Primes

leetcode-204-Count Primes

() tps data- top weight 般的 dsm get lin

Count Primes

Description:

Count the number of prime numbers less than a non-negative number, n.


題目 Count Primes



計算小於n的全部素數的總數。

用一般的方法超時,應該用篩選法求素數 ,參考 篩選法求素數

class Solution {
public:
       
    int countPrimes(int n) {
        int* a = new int[n]();
        int ans = 0;
        int m = sqrt(n);
        for (int i = 2;i <= m;i++) {
            if (!a[i]) {
                for (int j = i * i;j < n;j = j + i) a[j] = 1;// 標記因子為i的合數
            }
        }
        
        for (int i = 2;i < n;i++){
            if (!a[i]) ans++;
        }
        
        return ans;
    }
};


leetcode-204-Count Primes