zoukankan      html  css  js  c++  java
  • LeetCode

    原题

    原题链接

    Description:

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

    计算小于非负数n的素数个数。

    思路

    这题用埃拉托斯特尼筛法来做效果比较好,普通的方法基本会TLE。但是在用了埃拉托斯特尼筛法之后,还有一些细节值得注意:

    (1)首先我们该用 i*i<=n 替代 i<=sqrt(n) 来避免使用 sqrt() ,因为sqrt()的操作是比较expensive的。

    (2)当要表示两个状态的时候,首选是用bool而不是int来节省空间。这个以前也是知道的,但是具体写代码的时候经常没注意。

    (3)埃拉托斯特尼筛法只需要计算到 i*i<n 的部分即可。

    代码

    class Solution {
    public:
        int countPrimes(int n) {
            if(n<=2) return 0; 
            bool res[n];
            int ans=1;
            int i,j;
            for(i=3;i<n;i++)
                if(i%2==0) res[i]=false;
                    else res[i]=true;
            for(i=3;i*i<n;i+=2){
                if(!res[i]) continue;
                for(j=i;j*i<n;j+=2)
                    res[i*j]=false;
            }
            for(int i=3;i<n;i+=2)
                if(res[i]) ans++;
            return ans; 
        }
    };
    
  • 相关阅读:
    nginx平滑升级及回滚
    redis源码安装
    memcached安装
    Harbor源码部署
    Maven源码部署
    tomcat单机多实例(未完待续)
    部署tomcat
    nginx编译参数详解
    CentOS7 安装pip/pip3
    nginx 部署配置
  • 原文地址:https://www.cnblogs.com/rgvb178/p/6267491.html
Copyright © 2011-2022 走看看