zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】特殊数题3:204 Count Primes

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    204. Count Primes

    Count the number of prime numbers less than a non-negative number, n.
    Example:
    Input: 10
    Output: 4
    Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
     
    /*
    问题:
        数素数(质数)的个数(小于n)
    方法:
        Sieve of Eratosthenes solution
        用已经找到的质因子i去乘,去掉合数i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n
    举例:
     n = 16(小于n,故不包含15,创建15长度,p[0]无用,直观一点,以1算起,下标与数对应)
     p[0] = p[1] = false
     2: 4 6 8 10 12 14
     3: 9 12 15 
     sqrt(16) = 4
     
    */
    class Solution
    {
    public:
        int countPrimes(int n)
        {
            if(n <= 2) return 0;
            vector<bool> prime(n, true); //初始化为true
            prime[0] = prime[1] = false;
            for(int i = 2; i<sqrt(n); i++) //i = 2~sqrt(n)
            {
                if(prime[i])
                {
                    for(int j=i*i; j<n; j+=i) prime[j] = false; //j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n,均不是质数
                }
            }
           
            return count(prime.begin(), prime.end(), true);
        }
    };
    /*
    也可直接这样计数,比count函数更快
            int result = 0;
            for (int ii = 2; ii < n; ++ii)
            {
                if (is_prime[ii]) result++;
            }
    */
     
     
  • 相关阅读:
    Seafile V4.1 安装笔记
    mysql int(3)与int(11)的区别
    python命令行参数处理模块 optparse 使用参考
    Python标准库 urllib2 的使用
    Python默认模块 os和shutil 实用函数
    ApacheBench 使用教程
    ThinkPHP中PATHINFO模式优化
    Perl中的特殊内置变量详解
    Perl内置变量速查表
    eclipse jetty debug
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225072.html
Copyright © 2011-2022 走看看