zoukankan      html  css  js  c++  java
  • Count Primes

    Description:

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

     1 public class Solution {
     2     public int countPrimes(int n) {
     3         if(n <= 2) return 0;
     4         boolean[] arr = new boolean[n];//use false to represent prime numbers
     5         //Actually here only use 1 ~ n-1
     6         int sqr = (int)Math.sqrt(n - 1);
     7         for(int i = 2; i <= sqr; i ++){
     8             if(!arr[i]){
     9                 for(int j = i * i; j < n; j += i){
    10                     arr[j] = true;
    11                 }
    12             }
    13         }
    14         int count = 0;
    15         for(int i = 2; i < n; i ++){
    16             if(!arr[i]) count ++;
    17         }
    18         return count;
    19     }
    20 }

    Another Solution:

     1 public class Solution {
     2     public int countPrimes(int n) {
     3         if(n < 3) return 0;
     4         HashSet<Integer> primes = new HashSet<Integer> ();
     5         for(int i = 2; i < n; i ++){
     6             if(primes.isEmpty()){
     7                 primes.add(i);
     8             }else{
     9                 Iterator it = primes.iterator();
    10                 boolean isPrime = true;
    11                 while(it.hasNext()){
    12                     Integer tmp = (Integer) it.next();
    13                     if(i % tmp == 0) isPrime = false;
    14                 }
    15                 if(isPrime) primes.add(i);
    16             }
    17         }
    18         return primes.size();
    19     }
    20 }

    This one return Time Limit Exceeded for case: 499979

  • 相关阅读:
    GDOI模拟赛Round 1
    Codeforces 241B
    Codeforces 325E
    Codeforces 235E
    Codeforces 293B
    Codeforces 263E
    快速傅里叶变换FFT
    后缀自动机
    NOI2011 Day2
    NOI2014 Day2
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4465116.html
Copyright © 2011-2022 走看看