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}