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

Leetcode: Count Primes

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

Algorithm: The sieve of Eratosthenes, Referring to Summary: Primes

0 and 1 are not primes!

Maintain a notPrime boolean array. Start from the first prime 2, cross out all its multiples. The next number that is not crossed out is the next prime. Continue the process until reach n.

 1 public class Solution {
 2     public int countPrimes(int n) {
 3         if (n <= 1) return 0;
 4         boolean[] notPrime = new boolean[n+1];
 5         notPrime[0] = true;
 6         notPrime[1] = true;
 7         int count = 0;
 8         for (int i=2; i<n; i++) {
 9             if (!notPrime[i]) {
10                 count++;
11                 int mul = 2;
12                 while (i <= n/mul) {
13                     notPrime[i*mul] = true;
14                     mul++;
15                 }
16             }
17         }
18         return count;
19     }
20 }

 

posted @ 2015-12-15 03:09  neverlandly  阅读(275)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3