zoukankan      html  css  js  c++  java
  • Count Primes

    Description:

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

    //TLE
    class Solution {
    private:
        bool isPrime(int n) {
            if (n <= 1)
                return false;
            for (int i = 2; i * i <= n; i++) {
                if (n % i == 0)
                    return false;
            }
            return true;
        }
    public:
        int coutPrimes(int n) {
            int count = 0;
            for (int i = 1; i < n; i++) {
                if (isPrime(i))
                    count++;
            }
            return count;
        }
    };
    
    //筛数法
    class Solution2 {
    public:
        int countPrimes(int n) {
            if (n <= 1) return 0;
            bool* IsPrime = new bool[n];
            for (int i = 2; i < n; i++) {
                IsPrime[i] = true;
            }
    
            for (int i = 2; i * i < n; i++) {
                if (!IsPrime[i])
                    continue;
                for (int j = i * i; j < n; j += i) {
                    IsPrime[j] = false;
                }
            }
            int count = 0;
            for (int i = 2; i < n; i++) {
                if (IsPrime[i])
                    count++;
            }
            return count;
        }
    };
  • 相关阅读:
    awk
    tac
    cat
    less
    more
    head
    vim
    linux安装redis
    Redis for Python开发手册
    Python3.x标准模块库目录
  • 原文地址:https://www.cnblogs.com/wxquare/p/5937877.html
Copyright © 2011-2022 走看看