• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

leetcode-204-Count Primes

                                                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;
    }
};


posted on 2017-06-07 11:43  cynchanpin  阅读(156)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3