int countPrimes(int n) { unsigned char *map = (unsigned char *)calloc(n, sizeof(unsigned char)); int sq = (int)sqrt(n); for (int i = 2; i <= sq; i++) { // i 不需要遍历到 n,而只需到 sqrt(n) 即可 if (map[i] == 0) { for (int j = i * i; j < n; j += i) { // 把 i 的整数倍都标记排除 map[j] = 1; } } } int count = 0; for (int i = 2; i < n; i++) { if (map[i] == 0) { count++; } } return count; }