Java Prime Prime Numbers-leetcode 204

Source: Internet
Author: User
Tags bitset square root

Description:

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

Click to show more hints.

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

For all primes within N, previously seen a topic, by marking out all non-primes, and then finding the prime number, the code is as follows:

1      Public intCountPrimes (intN) {2         if(n = = 0 | | n = = 1 | | n = = 2)3             return0;4         int[] flag =New int[n];5          for(inti = 2; I < math.sqrt (flag.length); i++) {6             if(Flag[i] = = 0)7                  for(intj = i; I * J < flag.length; J + +) {8Flag[i * j] = 1;9                 }Ten         } One         intCount = 0; A          for(inti = 2; i < flag.length; i++) -Count + =Flag[i]; -BitSet bs =NewBitSet (); the bs.ne -         returnFlag.length-count-2; -}

It is worth noting that the outer loop only needs to be to the square root of N, because the inner loop begins with the i*j. In Leetcode, if no Gargan, it will overflow.

Java Prime Prime Numbers-leetcode 204

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.