204. Count Primes

来源:互联网 发布:java方法调用范围 编辑:程序博客网 时间:2024/06/17 20:03
Count the number of prime numbers less than a non-negative number, n.

大致思路差不多 答案要简洁一些 注意结束条件 不是 i<num/2 而是i*i<=num 

public int countPrimes(int n) {    boolean[] notPrime = new boolean[n];    int count = 0;    for (int i = 2; i < n; i++) {        if (notPrime[i] == false) {            count++;            for (int j = 2; i*j < n; j++) {                notPrime[i*j] = true;            }        }    }        return count;}

it starts from 2, the first prime, then mark the multip of 2 as true in notPrime, so the loop of i will skip them. the next prime is 3, do the same thing. Then it is 4, which 2*2, so the not prime is true, and will skip to next.
原创粉丝点击