LeetCode-204 Count Primes

Source: Internet
Author: User

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

Test instructions: The number of all primes less than n.

Ideas:

1. Scope in the 1~n-1, the first to remove the multiples of 2, and then delete the multiples of 3, and then delete the multiples of 5 ... Each time you delete a multiple of the smallest element in the collection, the remaining elements are the prime number after multiple loops.

2. However, to save a 1~n-1 integer set, if n is large, then it is possible that the set will not fit, all attempts to solve with Bitset, the K-bit represents the integer k+1;

3. If the K-bit is 0, then the prime number is 1, and the non-prime number is indicated;

The code is as follows:

 Public intCountPrimes (intN) {if(N < 3)return0; BitSet BS=NewBitSet (n-1); Bs.clear (1); Bs.set (0); intCount = N-2;  for(intI=1; I<n-1; ) {             for(intj=2*i+1; j<n-1; j=j+ (i+1)) {                if(!Bs.get (j))                    {Bs.set (j); Count--; }} I= Bs.nextclearbit (i+1); }        returncount; }

LeetCode-204 Count Primes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.