zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    React之Antd组件<Input />属性defaultValue问题记录。
    java多继承问题
    python多继承问题
    React之state
    概念题
    修复linux的yum源
    stl
    java
    python
    各种执行方式
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5047018.html
Copyright © 2011-2022 走看看