1. 程式人生 > >Count Primes

Count Primes

lee blog spec clas add public test credit code

Description:

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

我們考慮1-n的數 我們只需要考慮他們是否為素數 可以用bitset做

對於一個數,我們可以一次性將它的倍數設置為true

這樣false位的數就是素數

public int countPrimes(int n) {
    BitSet bs = new
BitSet(n); int count = 0; for(int i=2;i<n;i++) { if(!bs.get(i)) { count ++; for(int j=2;j*i<n;j++) bs.set(j*i); } } return count; }

Count Primes