LeetCode OJ Count Primes

前端之家收集整理的这篇文章主要介绍了LeetCode OJ Count Primes前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Description:

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

click to show more hints.

Credits:

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

素数挑选法。

int countPrimes(int n) { bool * IsPrime = (bool*)malloc(sizeof(bool) * n); for (int i = 0; i < n; i++) IsPrime[i] = true; for (int i = 2; i < n; i++) { if (IsPrime[i]) { for (int j = i + i; j < n; j += i) { IsPrime[j] = false; } } } int ans = 0; for (int i = 2; i < n; i++) if (IsPrime[i]) ans++; free(IsPrime); return ans; }

猜你在找的PHP相关文章