204. Count prime numbers

Source: Internet
Author: User

Count All integers smaller than non-negative integersNNumber of prime numbers.

Example:

Input: 10 output: 4 explanation: There are four prime numbers smaller than 10, which are 2, 3, 5, and 7.
/* Int countprimes (int n) {int COUNT = 0; If (n = 0 | n = 1) return 0; For (Int J = 2; j <= N; j ++) {If (isprime (j) Count ++;} return count;}/* bool isprime (int n) {If (n <2) return false; For (INT I = 2; I * I <= N; I ++) {If (N % I = 0) return false;} return true;} * // * bool isprime (INT num) {If (Num <= 3) {return 2 ;} // If (Num % 6! = 1 & num % 6! = 5) {return false;} For (INT I = 5; I * I <num; I + = 6) {If (Num % I = 0 | num % (I + 2) = 0) {return false ;}} return true ;}*/INT countprimes (INT N) {int sum = 0; If (n = 0 | n = 1) return 0; For (INT I = 2; I <n; I ++) {If (isprime (I) sum ++;} return sum;} bool isprime (INT num) {If (num = 2 | num = 3) return true; // If (Num % 6! = 1 & num % 6! = 5) return false; int TMP = SQRT (Num); // either of the multiples of 6 May not be a prime number for (INT I = 5; I <= TMP; I + = 6) if (Num % I = 0 | num % (I + 2) = 0) return false; // exclude all, the remainder is the prime number return true ;}

/* For further analysis, another feature of prime number is that it is always 6 x-1 or 6 x + 1, where X is a natural number greater than or equal to 1.

 

It is not difficult to prove this conclusion. First, 6x is definitely not a prime number, because it can be divisible by 6; secondly, 6x + 2 is certainly not a prime number, because it can also be divisible by 2; and so on, 6x + 3 can certainly be divided by 3; 6x + 4 can certainly be divided by 2. Then, only 6x + 1 and 6X + 5 (equivalent to 6x-1) may be prime numbers. So the cycle step can be set to 6, and then only the number of the six sides can be determined at a time. */

 

204. Count prime numbers

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.