204 Count Primes

Source: Internet
Author: User


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

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

Statistical prime: Given a nonnegative integer n, the number of prime numbers smaller than n is counted. This problem at first glance is very simple, is to write a function to determine whether it is a prime number, and then the N-cycles. However, the test data will appear very large n, and the normal method will run the timeout. The traditional method of determining whether a number is prime is the time complexity of O (log2n) (compared with the square root n), and the time complexity of the n number is multiplied by N.

Leetcode the topic as simple, because he gave a series of hints and gave another algorithm, with more memory in exchange for shorter time. The overall idea is to generate an array of n (n input) elements (initialized to 0), start from 4 to N to end all the composite set to 1, and then 2 times the group, encountered as 0 element count plus one. I first stuck the code below, can not see the leetcode of the topic link https://leetcode.com/problems/count-primes/above has a complete hints

1 classSolution {2  Public:3     voidSetflag (vector<int>& VEC,intNintmax) {4         Long Long intt = N;//convert growth long shaping, otherwise n squared may overflow5          for(Long Long inti = t * t; i < Max; i + =N) {6Vec[i] =1;7         }8     }9     intCountPrimes (intN) {Ten         if(N <3)return 0; One         //int *vec = (int *) malloc (sizeof (int) * n); Avector<int> Vec (n +1,0); -          for(inti =2; I < n; i++) { - Setflag (VEC, I, n); the         } -         intCount =0; -          for(intj =2; J < N; J + +) { -             if(!Vec[j]) { +count++; -             } +         } A         returncount; at     } -};
View Code

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.