码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Count Primes

时间:2015-12-15 06:27:06      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Leetcode: Count Primes

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5047018.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!