首页 > 其他 > 详细

Leetcode: Count Primes

时间:2015-12-15 06:25:11      阅读:246      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!