204. Count Primes, 204 countprimes

Source: Internet
Author: User

204. Count Primes, 204 countprimes

Description:

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

 

1 int countPrimes (int n) {2 bool * isprime = (bool *) malloc (n * sizeof (bool); 3 int I, j; 4 int count; 5 if (n <= 2) 6 return 0; 7 if (n = 3) 8 return 1; 9 count = n-2; // remove 1 not a prime number, 2 is a prime number, and the remaining conut calculates the number of prime numbers, that is, minus the sum of 3 to n 10 for (I = 3; I <n; I ++) 11 {12 if (I % 2) 13 isprime [I] = true; 14 else {// remove the total number of power of 2 15 isprime [I] = false; 16 count --; 17} 18} 19 for (I = 3; I * I <= n; I ++) // here, the author of n is determined, it is because all numbers between I and I * I will be determined to 20 {21 if (isprime [I]) // when I is a prime (PRIME) number, all multiples of I must be 22 {23 for (j = I * I; j <n; j + = I) 24 if (isprime [j]) // j starts from I * I, because I * (I-1) has been judged 25 {26 isprime [j] = false; 27 count --; // remove the total number from the total number to the total number 28} 29} 30} 31 free (isprime); 32 return count; 33 34}

 

Related Article

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.